0% found this document useful (0 votes)
114 views

DBMS Lab Manual

Thus various simple SQL queries were written and practiced on the EMP table to retrieve the required information.

Uploaded by

Senthil Prakash
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views

DBMS Lab Manual

Thus various simple SQL queries were written and practiced on the EMP table to retrieve the required information.

Uploaded by

Senthil Prakash
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 22

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB

LABORATORY LEARNING MATERIAL

DATABASE MANAGEMENT SYSTEMS LAB


DATABASE MANAGEMENT SYSTEMS LAB

LIST OF EXPERIMENTS

1. Creation of a database and writing SQL queries to retrieve information from the database.
2. Performing Insertion, Deletion, Modifying, Altering, Updating and Viewing records based on
conditions.
3. Creation of Views, Synonyms, Sequence, Indexes, Save point.
4. Creating an Employee database to set various constraints.
5. Creating relationship between the databases.
6. Study of PL/SQL block.
7. Write a PL/SQL block to satisfy some conditions by accepting input from the user.
8. Write a PL/SQL block that handles all types of exceptions.
9. Creation of Procedures.
10. Creation of PL/SQL blocks with exception handling mechanism
11. Creation of database triggers and functions

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


1
CONTENTS

S.NO NAME OF THE EXERCISE PAGE NO.

1 DDL- Data Definition, Table Creation, Constraints. 3

2 DML- Insert, Select Commands, Update & Delete Commands. 5

3 TCL –Rollback, Commit commands. 7

4 Writing and Practice of Simple Queries. 8

5 Nested Queries & Queries Using Group By And Other Clauses. 9

6 Problems Based On Views, Synonym, Sequence & Index. 11

7 Creating Database. 13

8 High Level Programming Language Extension (PL/SQL Blocks). 14

9 PL/SQL Procedures. 16

10 PL/SQL Functions. 18

11 Exceptions 19

12 Triggers 20

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


2
1. DDL COMMANDS

AIM:

To create, alter, truncate and drop a table using DDL commands.

DDL COMMANDS:

OVERVIEW:
CREATE - to create objects in the database
ALTER - alters the structure of the objects in the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the records are
removed
COMMENT - add comments to the data dictionary
GRANT - gives user's access privileges to database
REVOKE - withdraw access privileges given with the GRANT command

SQL - CREATE TABLE

Syntax: CREATE TABLE tablename (column_name data_ type constraints, …)

Example:

INPUT::

SQL> CREATE TABLE DEPARTMENT ( DEPTID VARCHAR(5) CONSTRAINT PKEY PRIMARY KEY,

DEPTNAME VARCHAR(15), DOS DATE CONSTRAINT NOTNULL );

OUTPUT: Table created.

SQL> CREATE TABLE EMPLOYE ( EMPID VARCHAR(5) CONSTRAINT PKEY PRIMARY KEY,

EMPNAME VARCHAR(15), JOB CHAR(10) CONSTRAINT UNIQ1 UNIQUE,

MGRID VARCHAR(5) CONSTRAINT FKEY1 REFERENCES EMP (EMPID),

HIREDATE DATE, DEPTID VARCHAR(5) CONSTRAINT FKEY2 REFERENCES DEPT(DEPTID),

SALARY NUMBER(7,2));

OUTPUT: Table created.

SQL - DESC TABLE

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


3
SQL>desc Employe;

Name Null? Type

--------------------------------- -------- ----------------------------

EMPID NOT NULL VARCHAR2(5)

EMPNAME VARCHAR2(20)

JOB NOT NULL CHAR(10)

MGRID NOT NULL VARCHAR2(5)

HIREDATE DATE

DEPTID VARCHAR2(5)

SALARY NUMBER(7,2)

SQL - ALTER TABLE

INPUT::

SQL>ALTER TABLE EMPLOYE ADD CONSTRAINT NTNLL NOT NULL (SALARY);

OUTPUT: Table Altered.

Similarly, ALTER TABLE EMPLOYE DROP CONSTRAINT UNIQ1;

SQL - DROP TABLE

– Deletes table structure – Cannot be recovered – Use with caution

INPUT::

SQL> DROP TABLE EMP; Here EMP is table name

OUTPUT: Table Dropped.

SQL - TRUNCATE TABLE

TRUNCATE TRUNCATE TABLE <TABLE NAME>;

RESULT:

Thus the table was successfully created, altered, truncated, and dropped.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


4
2. DML COMMANDS

AIM:

To insert, select, update and delete records in a table using DML commands.

DML COMMANDS:

COMMANDS OVERVIEW:
SELECT - retrieve data from the a database
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain

SQL – SELECT FROM

Selecting all records from a table

SELECT * FROM EMPLOYE

Listing the selected records which satisfies the given condition from a table

SELECT * FROM EMPLOYE WHERE DEPTID=’DPT01’

SQL - INSERT INTO

Syntax: INSERT INTO tablename VALUES (value list)

Single-row insert

INSERT INTO DEPARTMENT VALUES (‘DPT02’,’TESTING’,’10-JAN-2012’)

Inserting one row, with values to the column in the given order

INSERT INTO DEPARTMENT (DEPTNAME, DEPTID) VALUES (‘DESIGN’, ‘DPT02’);

Inserting one or more rows with values from other tables.

INSERT INTO DEPARTMENT (DEPTID, DEPTNAME)

SELECT EMPID, EMPNAME FROM EMP WHERE MGRID=EMPID;

OTHER EXAMPLES:

INPUT::

SQL>INSERT INTO EMPLOYE VALUES (‘Emp121’,’Gayle’,’Testing’,’Emp01’,’01-Feb-2013’, ’Dpt01’, 32000);

OUTPUT: 1 row created.

INPUT::

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


5
SQL>INSERT INTO DEPARTMENT VALUES(‘&deptid,’&deptname’);

Enter value for deptid: Dpt01

Enter value for deptname: Development

OUTPUT:

old 1: Insert into department values(‘&deptid,’&deptname’)

new 1: Insert into department values(‘Dpt01’,' Development’)

1 row created.

SQL - UPDATE

Syntax: UPDATE tablename SET COLUMN_NAME =value [ WHERE CONDITION]

INPUT::

SQL> UPDATE DEPT SET DOS=’01-JAN-2010’ WHERE DEPTID=’DPT01’;

1 row updated.

SQL - DELETE FROM

Syntax: DELETE FROM tablename WHERE condition

INPUT::

SQL> DELETE FROM DEPARTMENT;

OUTPUT: 1 row deleted.

RESULT:

Thus the table was successfully inserted, updated, select, and deleted.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


6
3. TCL COMMANDS

AIM:

To create save point, commit and rollback while using a transaction.

TCL COMMANDS:

COMMANDS OVERVIEW

COMMIT - save work done & it is visible to other users.


SAVEPOINT - identify a point in a transaction to which you can later roll back
ROLLBACK - restore database to original since the last COMMIT
SET TRANSACTION - Change transaction options like what rollback segment to use

SAVEPOINT
Syntax: savepoint username;
INPUT::
SQL> savepoint emp;
Output:
savepoint created;

COMMIT
Syntax: commit;
INPUT::
SQL> commit;
Output:
Commit complete.

ROLLBACK
Syntax:
rollback to savepoint_text_identifier;
INPUT::
SQL> rollback to emp;
Output:
Rollback complete.

RESULT:

Thus the table was successfully saved, committed and rollback.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


7
4. WRITING AND PRACTICE OF SIMPLE QUERIES

AIM:

To write simple SQL queries and to practice them.

PROBLEM STATEMENTS:

REFERRED TABLE: emp(empno, ename,job,mngr,hiredate,sal,comm, deptno, age, esal)


1. Get the description of EMP table.

2.List all employee details.

3. List all employee names and their salaries, whose salary lies between 1500/- and 3500/- both inclusive.

4. List all employee names and their and their manager whose manager is 7902 or 7566 0r 7789.

5. List all employees which starts with either J or T.

6. List all employee names and jobs, whose job title includes M or P.

7. List all jobs available in employee table.

8. List all employees who belongs to the department 10 or 20.

9. List all employee names , salary and 15% rise in salary.

10. List minimum, maximum, average salaries of employee.

11. Find how many job titles are available in employee table.

12. What is the difference between maximum and minimum salaries of employees in the organization?

13. Display all employee names and salary whose salary is greater than minimum salary of the company and job title starts
with ‘M’.

14. Find how much amount the company is spending towards salaries.

15. Display name of the dept. with deptno 20.

16. List ename whose commission is NULL.

17. Find no.of dept in employee table.

18. List ename whose manager is not NULL.

19. Calculate the experience in years of each programmer and display along with their name in descending order.

20 . In which month most number of programmers has joined.

RESULT:
Thus the given problem statements were solved using simple queries.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


8
5. NESTED QUERIES & QUERIES USING GROUP BY AND OTHER CLAUSES

AIM:

To write queries using Set operations, to write nested queries and also to write queries using clauses such as GROUP BY,
ORDER BY, etc. and retrieving information by joining tables.

SET OPERATIONS & OTHER CLAUSES:


NESTED QUERY: - A nested query makes use of another sub-query to compute or retrieve
the information.
UNION - OR
INTERSECT - AND
EXCEPT - NOT
Order by : The order by clause is used to display the results in sorted order.
Group by : The attribute or attributes given in the clauses are used to form groups. Tuples with the
same value on all attributes in the group by clause are placed in one group.
Having: SQL applies predicates (conditions) in the having clause after groups have been formed, so
aggregate function be used.

PROBLEM STATEMENTS:

REFERRED TABLE:

programmer(pname, job_title, dob, doj, gender, salary)

software(pname, title, develop_lang, scost, dcost)

studies(pname, institute, city)

1. Find the name of the institute in which the person studied and developed the costliest package.

2. Find the salary and institute of a person who developed the highest selling package.

3. How many packages were developed by the person who developed the cheapest package.

4. Display the title, scost, dcost, difference of scost and dcost in the descending order of difference.

5. Display the details of these programmer WHO joined BEFORE 2015.

6. Display the details of those who draw the same salary.

7. Display total salary spent for each job category.

8. Display the sales cost of package developed by each programmer.

9. Display the number of packages sold by each programmer.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


9
10. Display the number of packages in each language for which the development cost is less than thousand.

11. Display each institute name with number of students.

12. In which institutes did the person who developed the COSTLIEST package.

13. How many copies of package have the least difference between development and selling cost, were sold?

14. Which is the costliest package developed in Pascal.

15. Which language was used to develop most no .of packages?

16. Who are the male programmers earning below the average salary of female programmers?

17. Display the details of software developed by the male programmers earning more than 3000/-.

18. Display the details of software developed in c language by female programmers of Pragathi.

RESULT:

Thus the given problem statements were solved using nested queries and group by & other clauses.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


10
6. PROBLEMS BASED ON VIEWS, SYNONYM, SEQUENCE & INDEX

AIM:

To solve the problem statements based on views, synonym, sequence and Indexes.

OVERVIEW:

VIEW:

A view is simply the representation of a SQL statement that is stored in memory so that it can easily be re-used. Its
also referred as logical table.

SYNTAX:

CREATE OR REPLACE VIEW <view name > AS < select statement >

SYNONYM:

A synonym is an alias or alternate name for a table, view, sequence, or other schema object. They are used mainly to
make it easy for users to access database objects owned by other users.

SYNTAX:

CREATE OR REPLACE SYNONYM <synonym_name> FOR <object_name>

SEQUENCE:

A sequence is a database object from which multiple users may generate unique integers. User can use sequences to
automatically generate primary key values.

INDEXES:

Database system uses indexes to avoid the need for large-table, full-table scans and disk sorts, which are required
when the SQL optimizer cannot find an efficient way to service the SQL query.

SYNTAX:
CREATE INDEX <index_name> ON <table_name(attribute)>

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


11
PROBLEM STATEMENTS:

1. Create a view from single table containing all columns from the base table.

2. Create a view from single table with selected columns.

3. Create a view from two tables with all columns.

4. Create a view from two tables with selected columns.

5. Check all DML commands with above 4 views.

6. Create a sequence to generate unique value for empid field in the employee table while inserting.

7. Create index for city attribute in employee table.

RESULT:

Thus the given problem statements based on views, synonyms, sequences and indexes were solved.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


12
7. CREATING DATABASE

AIM:

To create database and also to create relationship among database.

COMMAND OVERVIEW:

SYNTAX:
CREATE DATABASE [ database ]
{ USER SYS IDENTIFIED BY password
| USER SYSTEM IDENTIFIED BY password
| CONTROLFILE REUSE
| MAXDATAFILES integer
| MAXINSTANCES integer
| CHARACTER SET charset
| NATIONAL CHARACTER SET charset
| SET DEFAULT
{ BIGFILE | SMALLFILE } TABLESPACE
| database_logging_clauses
| tablespace_clauses
| set_time_zone_clause
};

PROBLEM STATEMENT:

1. Create a new database by the name student_db with required features.

RESULT:

Thus the database was created with the specified parameters.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


13
8. HIGH LEVEL PROGRAMMING LANGUAGE EXTENSION (PL/SQL BLOCKS)
AIM:
To solve the given problem statements using PL/SQL blocks.

PL/SQL BLOCK:
PL/SQL is a block-structured language, meaning that PL/SQL programs are divided and written in logical blocks of
code. Each block consists of three sub-parts:

1. Declarations: This section starts with the keyword DECLARE. It is an optional section and defines all variables, cursors,
subprograms, and other elements to be used in the program.
2: Executable Commands: This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It
consists of the executable PL/SQL statements of the program. It should have at least one executable line of code, which may be
just a NULL command to indicate that nothing should be executed.
3: Exception Handling: This section starts with the keyword EXCEPTION. This section is again optional and contains
exception(s) that handle errors in the program.

Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL blocks using BEGIN and
END.

SYNTAX:
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;

PROBLEM STATEMENTS:
REFERED TABLES:
employee(emp_id,emp_name,dept_id,basic,hra,da,pf,net);

1. Create a PL/SQL block for inserting values in the Employee table. Only emp_id, emp_name, department & basic
should be received as input while executing the block and for the rest of the fields the values need to be calculated as given
below.
Calculations:

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


14
HRA=50% OF BASIC
DA=20% OF BASIC
PF=7% OF BASIC
NETPAY=BASIC+DA+HRA-PF

2. Create a PL/SQL block for updating records in Employe table where the user should provide the emp_id and the new
basic salary and thus the HRA,DA, PF and NETPAY should get calculated and updated accordingly.

3. Create a PL/SQL block for showing the new netpay after getting new basic salary for a particular employee. Display the new
netpay along the old netpay without updating in the table. Also If no customer found with the given customer id then show
appropriate error message.

RESULT:
Thus PL/SQL statements were written for inserting & updating the rows in the EMPLOYE table.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


15
9. PROCEDURES

AIM:

To solve the given problem statements using procedures.

PL/SQL PROCEDURES:

An Oracle stored procedure is a program stored in an Oracle database. The following are the advantages of using
procedures.

Better performance: Oracle stored procedures load once into the shared pool and remain there unless they become
paged out. Subsequent executions of the Oracle stored procedure are far faster than executions of external code.

Coupling of data with behaviour: DBAs can use naming conventions to couple relational tables with the behaviors
associated with a table by using Oracle stored procedures as "methods". If all behaviors associated with the employee table
are prefixed with the table name--employee.hire, employee.give_raise, for example--the data dictionary can be queries to list
all behaviors associated with a table (select * from dba_objects where owner = 'EMPLOYEE'), and it's easy to identify and
reuse code via stored procedures.

Isolation of code: Since all SQL is moved out of the external programs and into the Oracle stored procedures, the
application programs become nothing more than calls to Oracle stored procedures. As such, it becomes very simple to swap
out one database and swap in another one.

SYNTAX:

CREATE [OR REPLACE] PROCEDURE procedure_name (parameters list)


IS
<declaration_section>

BEGIN
<executable_section>

EXCEPTION
<exception_section>

END;

PROBLEM STATEMENTS:
REFERRED TABLES:

Borrow(acc_no , rollno, date_issue);

1. Write a procedure to insert a record in borrower relation. Before inserting check whether the book is available or not.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


16
2. Write a procedure to insert a record in borrower relation with the above constraints and also ensure that the member
has not borrowed more than three books.

Result:
Thus PL/SQL Procedures were created to solve the given problem statements.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


17
10. FUNCTIONS

AIM:

To solve the given problem statements using PL/SQL functions.

PL/SQL FUNCTION:

A PL/SQL function is same as a procedure except that it returns a value. A standalone function is created using the
CREATE FUNCTION statement.

SYNTAX

CREATE [OR REPLACE] FUNCTION function_name (parameter_name [IN | OUT | IN OUT] type [, ...])

RETURN return_datatype

{IS | AS}

BEGIN

< function_body >

END;

PROBLEM STATEMENT:

REFERRED TABLES:

transaction(accno number(5), amount number(7,2), trans_type varchar(5),dot date);

1. Create a function to insert the records into the transaction table, after performing each transaction in the transaction
table show the net balance of the particular account.

2. Write a function to return the balance amount available in the particular account by summing all the credited amount
in the account and summing all the debited amount from the account and then subtracting both the values.

RESULT:
Thus PL/SQL functions were created to solve the given problem statements.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


18
11. EXCEPTIONS
AIM:
To solve the given problem statements using exception handling mechanism in PL/SQL.

EXCEPTION HANDLING IN PL/SQL:


An exception is an error condition during a program execution. PL/SQL supports programmers to catch such
conditions using EXCEPTION block in the program and an appropriate action is taken against the error condition. There are
two types of exceptions:
 System-defined exceptions
 User-defined exceptions
Syntax:
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
........
WHEN others THEN
exception3-handling-statements
END;

PROBLEM STATEMENT:
Referred Tables: Books(acc_no, title, author, publisher, price, pub_year)
1. Write a PL/SQL procedure to display title, author, publisher of the given access number (acc_no). If the given access
number is not available then display ‘No such books!’ using exception handling mechanism.
2. Write a PL/SQL procedure to display title, author and published year of the given access number. If the given access
number is not a valid number then display ‘Access number must a positive number’ using user defined exceptions.

RESULT:
Thus PL/SQL procedures with exception handling were created to solve the given problem statements.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


19
12. TRIGGERS
AIM:
To solve the given problem statements using triggers.

PL/SQL TRIGGERS:
Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact,
written to be executed in response to any of the following events:
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is associated.
Benefits of Triggers
Generating some derived column values automatically
Enforcing referential integrity
Event logging and storing information on table access
Auditing
Synchronous replication of tables
Imposing security authorizations
Preventing invalid transactions.

SYNTAX:
CREATE OR REPLACE TRIGGER < trigger_name >
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name]
ON < table_name >
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN < condition >
DECLARE
< Declaration-statements >
BEGIN
< Executable-statements >
EXCEPTION
< Exception-handling-statements >
END;

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


20
PROBLEM STATEMENT:

REFERRED TABLES:

Account ( accnt_no,cst_id,acnt_type,last_trans_date,balance )

Account_bckup(accnt_no,last_trans_date,balance)

Loan (ln_id,cst_id,ln_amount,ln_date);

1. Create a trigger for Account relation such that whenever a record is inserted in the Account table the same record
also gets inserted in the backup table.

2. Create a trigger for account relation such that whenever account record is inserted in account relation with negative
relation then that record should also be inserted in the loan relation with positive balance.

Result:
Thus the triggers were created accordingly to solve the given problem statements.

UCSE253P - DATABASE MANAGEMENT SYSTEMS LAB


21

You might also like