Page 1
ACHARYA NAGARJUNA UNIVERSITY
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CHALAPATHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
III/IV B. Tech I SEM, 2020-21
MASTER LAB MANUAL
For
DATABASE MANAGEMENT SYSTEMS LAB
Prepared by
G.RAMACHANDRA RAO Assistant Professor
CHALAPATHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(AUTONOMOUS)
CHALAPATHI NAGAR, LAM, GUNTUR-522034
Page 2
INDEX
S.NO CONTENT Page
No
i Vision and Mission 1
ii POs and PEOs 2-3
iii Course Objectives and Outcomes 4
iv Mapping 4-5
iv Syllabus 6
1
Learn the Data Definition Language (DDL) commands in RDBMS, Data
Manipulation Language (DML) and Data Control Language (DCL). 7-18
2
Simple queries: selection, projection, sorting on a simple table, Small-large number
of attributes ,Distinct output values ,Renaming attributes , Computed attributes
Simple-complex conditions (AND, OR, NOT).
19-32
3
Partial Matching operators (LIKE, %, _, *, ?) ,ASC-DESC ordering combinations
Checking for Nulls. 33-36
4
Multi-table queries (JOIN OPERATIONS) ,Simple joins (no INNER JOIN)
Aliasing tables – Full/Partial name qualification ,Inner-joins (two and more
(different) tables) ,Inner-recursive-joins (joining to itself) ,Outer-joins (restrictions
as part of the WHERE and ON clauses) ,Using where & having clauses.
37-43
5
Nested queries :In, Not In Exists, Not Exists Dynamic relations (as part of
SELECT, FROM, and WHERE clauses). 44-50
6 Set Oriented Operations :Union, Difference, Intersection, Division.
51-55
7
PL/SQL Programming I :Programs using named and unnamed blocks, Programs
using Cursors, Cursor loops and records. 56-65
8 PL/SQL Programming II :Creating stored procedures, functions
66-72
9 Triggers and auditing triggers
73-77
ADDITIONAL EXPERIMENTS
1 To Check whether a number is Armstrong or not using functions.
78
2 To Perform Banking Operations Using Procedures
79-80
Page 3
DBMS LAB
1
CHALAPATHI INSTITUTE OF ENGINEERING & TECHNOLOGY
CHALAPATHI NAGAR, LAM, GUNTUR-522034
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
COLLEGE VISION:
To emerge as an Institute of Excellence for Engineering and Technology and provide world-
class education and research opportunities to the students catering the needs of society.
COLLEGE MISSION:
Establishing a state-of-the-art Engineering Institute with continuously improving
infrastructure and produce students with innovative skills and global outlook.
DEPARTMENT VISION:
To produce professionally competent, research oriented and socially sensitive engineers and
technocrats in the emerging technologies.
DEPARTMENT MISSION:
DM 1: State of art laboratories to meet the needs of the continuous change.
DM 2: Provide a research environment to meet the societal issues.
DM 3: Facilitating collaborations/MOU’S towards emerging technologies.
Page 4
DBMS LAB
2
CHALAPATHI INSTITUTE OF ENGINEERING & TECHNOLOGY
CHALAPATHI NAGAR, LAM, GUNTUR-522034
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
PEO’s:
PEO-1: To prepare students to excel in computer industry profession or higher studies
through quality education
PEO-2: To analyse real life problems, design computing systems appropriate to its solutions
by exhibiting professionalism and team work
PEO-3: To demonstrate their ability to a rapidly changing environment by engaging in life
long learning.
PO’s:
1. ENGINEERING KNOWLEDGE: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of complex
engineering problems.
2. PROBLEM ANALYSIS: Identify, formulate, research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. DESIGN/DEVELOPMENT OF SOLUTIONS: Design solutions for complex
engineering problems and design system components or processes that meet the specified
needs with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
4. CONDUCT INVESTIGATIONS OF COMPLEX PROBLEMS: Use research-based
knowledge and research methods including design of experiments, analysis and interpretation
of data, and synthesis of the information to provide valid conclusions.
5. MODERN TOOL USAGE: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.
6. THE ENGINEER AND SOCIETY: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
7. ENVIRONMENT AND SUSTAINABILITY: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the knowledge
of, and need for sustainable development.
Page 5
DBMS LAB
3
8. ETHICS: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. INDIVIDUAL AND TEAM WORK: Function effectively as an individual, and as a
member or leader in diverse teams, and in multidisciplinary settings.
10. COMMUNICATION: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, give and
receive clear instructions.
11. PROJECT MANAGEMENT AND FINANCE: Demonstrate knowledge and
understanding of the engineering and management principles and apply these to one’s own
work, as a member and leader in a team, to manage projects and in multidisciplinary
environments.
12. LIFE-LONG LEARNING: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of technological
change.
PSO’s:
A graduate of the Computer Science and Engineering Program will demonstrate:
PSO1: Professional Skills: The ability to understand, analyze and develop computer
programs in the areas related to algorithms, system software, multimedia, web design, big
data analytics, and networking for efficient design of computer-based systems of varying
complexity.
PSO2: Problem-Solving Skills: The ability to apply standard practices and strategies in
software project development using open-ended programming environments to deliver a
quality product for business success.
PSO3: Successful Career and Entrepreneurship: The ability to employ modern computer
languages, environments, and platforms in creating innovative career paths to be an
entrepreneur, and a zest for higher studies.
Page 6
DBMS LAB
4
CHALAPATHI INSTITUTE OF ENGINEERING AND TECHNOLOGY CHALAPATHI NAGAR, LAM, GUNTUR
CLASS: III/IV B.Tech-I Sem BRANCH: CSE
DATABASE MANAGEMENT SYSTEMS LAB
Course Objectives
1. Describe the basics of SQL and construct queries using SQL.
2. To demonstrate use of constraints and relational algebra operations.
3. To emphasize the importance of cursors,packages,Triggers,procedures.
4. To facilitate students in Database design
Course Outcomes
After Completion of this Lab Students will be able
C352.1 Design and implement a database schema for a given problem domain.
C352.2 Use the basics of SQL and construct queries using SQL in database creation and
interaction.
C352.3 Implement PL/SQL Programs including stored procedures,functions & packages.
C352.4 Implement programs on Triggers.
Mapping of CO’s and PO’s CO’s PO’S
1 2 3 4 5 6 7 8 9 10 11 12
C352.1 2 3 2
C352.2
2 3 2
C352.3 3 2
C352.4 3 2
1-HIGH 2-MEDIUM 3-LOW
Page 7
DBMS LAB
5
CHALAPATHI INSTITUTE OF ENGINEERING & TECHNOLOGY
CHALAPATHI NAGAR, LAM, GUNTUR-5220L4
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
EXP
NO
List of Experiments
Course
outcomes
attained
Program
outcomes
attained
1
Learn the Data Definition Language (DDL) commands in
RDBMS, Data Manipulation Language (DML) and Data
Control Language (DCL).
C352.1
C352.2
PO2,PO3,PO5
2
Simple queries: selection, projection, sorting on a simple table,
Small-large number of attributes ,Distinct output values
,Renaming attributes , Computed attributes Simple-complex
conditions (AND, OR, NOT).
C352.1
C352.2
PO2,PO3,
PO5
3
Partial Matching operators (LIKE, %, _, *, ?) ,ASC-DESC
ordering combinations Checking for Nulls.
C352.1
C352.2
PO2,PO3,
PO5
4
Multi-table queries (JOIN OPERATIONS) ,Simple joins (no
INNER JOIN) Aliasing tables – Full/Partial name qualification
,Inner-joins (two and more (different) tables) ,Inner-recursive-
joins (joining to itself) ,Outer-joins (restrictions as part of the
WHERE and ON clauses) ,Using where & having clauses.
C352.1
C352.2
PO2,PO3,
PO5
5
Nested queries :In, Not In Exists, Not Exists Dynamic relations
(as part of SELECT, FROM, and WHERE clauses).
C352.1
C352.2
PO2,PO3,
PO5
6
Set Oriented Operations :Union, Difference, Intersection,
Division.
C352.1
C352.2
PO2,PO3,
PO5
7
PL/SQL Programming I :Programs using named and unnamed
blocks, Programs using Cursors, Cursor loops and records.
C352.3 PO3, PO5
8
PL/SQL Programming II :Creating stored procedures,
functions
C352.3 PO3, PO5
9 Triggers and auditing triggers C352.4 PO3, PO5
ADDITIONAL PROGRAMS
1 To Check whether a number is Armstrong or not using
functions.
C352.3 PO3, PO5
2 To Perform Banking Operations Using Procedures
C352.3 PO3, PO5
Page 8
DBMS LAB
6
Syllabus as per University
EXP.NO List of Experiments
1 Learn the Data Definition Language (DDL) commands in RDBMS, Data
Manipulation Language (DML) and Data Control Language (DCL).
2
Simple queries: selection, projection, sorting on a simple table, Small-large
number of attributes ,Distinct output values ,Renaming attributes , Computed
attributes Simple-complex conditions (AND, OR, NOT).
3
Partial Matching operators (LIKE, %, _, *, ?) ,ASC-DESC ordering combinations
Checking for Nulls.
4
Multi-table queries (JOIN OPERATIONS) ,Simple joins (no INNER JOIN)
Aliasing tables – Full/Partial name qualification ,Inner-joins (two and more
(different) tables) ,Inner-recursive-joins (joining to itself) ,Outer-joins
(restrictions as part of the WHERE and ON clauses) ,Using where & having
clauses.
5
Nested queries :In, Not In Exists, Not Exists Dynamic relations (as part of
SELECT, FROM, and WHERE clauses).
6 Set Oriented Operations :Union, Difference, Intersection, Division.
7
PL/SQL Programming I :Programs using named and unnamed blocks, Programs
using Cursors, Cursor loops and records.
8 PL/SQL Programming II :Creating stored procedures, functions
9 Triggers and auditing triggers
Page 9
DBMS LAB
7
EXPERIMENT-1
Aim: Learn the Data Definition Language (DDL) commands in RDBMS, Data Manipulation
Language (DML) and Data Control Language (DCL).
Program:
DDL Commands :
1. The Create Table Command: - it defines each column of the table uniquely. Each
column has minimum of three attributes, a name , data type and size.
Syntax:
Create table <table name> (<col1> <datatype>(<size>),<col2> <datatype><size>));
Ex:
create table emp(empno number(4) primary key, ename char(10));
2. Modifying the structure of tables.
a) Add new columns
Syntax:
Alter table <tablename> add(<new col><datatype(size),<new col>datatype(size));
Ex:
alter table emp add(sal number(7,2));
3. Dropping a column from a table.
Syntax:
Alter table <tablename> drop column <col>;
Ex:
alter table emp drop column sal;
4. Modifying existing columns.
Syntax:
Alter table <tablename> modify(<col><newdatatype>(<newsize>));
Ex:
alter table emp modify(ename varchar2(15));
5. Renaming the tables
Syntax:
Rename <oldtable> to <new table>;
Ex:
rename emp to emp1;
6. Truncating the tables.
Syntax:
Truncate table <tablename>;
Ex:
trunc table emp1;
7. Destroying tables.
Syntax:
Drop table <tablename>;
Ex:
Page 10
DBMS LAB
8
drop table emp;
DML commands :
1. Inserting Data into Tables: - once a table is created the most natural thing to do is load
this table with data to be manipulated later.
Syntax:
insert into <tablename> (<col1>,<col2>) values(<exp>,<exp>);
2. Delete operations.
a) Remove all rows
Syntax:
delete from <tablename>;
b) Removal of a specified row/s
Syntax:
delete from <tablename> where <condition>;
3. Updating the contents of a table.
a) Updating all rows
Syntax:
Update <tablename> set <col>=<exp>,<col>=<exp>;
b) Updating selected records.
Syntax:
Update <tablename> set <col>=<exp>,<col>=<exp> where <condition>;
4. Types of data constrains.
a) Not null constraint at column level.
Syntax:
<col><datatype>(size)not null
b) unique constraint
Syntax:
Unique constraint at column level.
<col><datatype>(size)unique;
c) unique constraint at table level:
Syntax:
Create table tablename(col=format,col=format,unique(<col1>,<col2>);
d) Primary key constraint at column level
Syntax:
<col><datatype>(size)primary key;
e) Primary key constraint at table level.
Page 11
DBMS LAB
9
Syntax:
Create table tablename(col=format,col=format Primary key(col1>,<col2>);
f) Foreign key constraint at column level.
Syntax:
<col><datatype>(size>) references <tablename>[<col>];
g) Foreign key constraint at table level
Syntax:
foreign key(<col>[,<col>])references <tablename>[(<col>,<col>)
h) Check constraint
check constraint constraint at column level.
Syntax:
<col><datatype>(size) check(<logical expression>)
i) Check constraint constraint at table level.
Syntax:
check(<logical expression>)
DCL commands:
Oracle provides extensive feature in order to safeguard information stored in its tables from
unauthoraised viewing and damage. The rights that allow the user of some or all oracle
resources on the server are called privileges.
a) Grant privileges using the GRANT statement
The grant statement provides various types of access to database objects such as tables, views
and sequences and so on.
Syntax:
GRANT <object privileges>
ON <objectname>
TO<username>
[WITH GRANT OPTION];
b) Revoke permissions using the REVOKE statement:
The REVOKE statement is used to deny the Grant given on an object.
Syntax:
REVOKE<object privilege> ON FROM<user name>;
Table Creation:
Syntax: create table <table_name> (c olumn1 datatype,column2 datatype...);
create table dept(deptnoint,dname char(10),location char(10),primary key(deptno));
Page 12
DBMS LAB
10
Output:
Table is created
Description of dept table
desc dept;
Table
Colu
mn
Data
Type
Len
gth
Preci
sion
Sc
ale
Primar
y Key
Null
able
Def
ault
Com
ment
DEPTS
DEPT
NO
Numbe
r - - 0 1 - - -
DNAM
E
Char 10 - - -
- -
LOCA
TION
Char 10 - - -
- -
1 - 3
Insert the values into the table:
insert into dept values(10,’Accounting’,’Newyork’);
Output:
1 row inserted
insert into dept values(20,’Research’,’Dallas’);
Output:
1 row inserted
insert into dept values(30,’sales’,’chicago’);
Output:
1 row inserted
insert into dept values(40,’operation’,’boston’);
Output:
1 row inserted
Display imformation of department table.
select * from dept;
DEPTNO DNAME LOCATION
10 accounting newyork
30 sales chicago
Page 13
DBMS LAB
11
20 research dallas
40 operation boston
Creation of Employee table
create table emp
(empno int,
empname char(10),
job char(10),
mgr int,
hiredate date,
salary int,
com int,
dno int,
primary key(empno),
foreign key(dno) references dept(deptno));
Output:
Table created
Description of dept table:
desc emp;
Output:
Tabl
e Column
Data
Type
Lengt
h
Preci
sion
Sca
le
Primar
y Key
Nullab
le Default
Com
ment
EMP EMPNO
Numbe
r - - 0 1 - - -
EMPNA
ME
Char 10 - - -
- -
JOB Char 10 - - -
- -
Page 14
DBMS LAB
12
Insertion of values into Employee table:
insert into emp values(7839,'king','president',NULL,'17-november-1981',5000,NULL,10);
Output:
1 row inserted
insert into emp values(7698,'blake','manager',7839,'1-may-1981',2850,NULL,30);
Output:
1 row inserted
insert into emp values(7782,'clark','manager',7839,'9-june-1981',2450,NULL,10);
Output:
1 row inserted
insert into emp values(7902,'ford','analyst',7566,'13-december-1981',3000,NULL,20);
Output:
1 row inserted
insert into emp values(7566,'jones','manager',7839,'2-april-1981',2975,NULL,20);
Output:
1 row inserted
insert into emp values(7788,'Scott','analyst',7566,'13-july-1987', 3000, NULL, 20);
Output:
1 row inserted
MGR
Numbe
r - - 0 -
- -
HIREDA
TE
Date 7 - - -
- -
SALARY
Numbe
r - - 0 -
- -
COM
Numbe
r - - 0 -
- -
DNO
Numbe
r - - 0 -
- -
1 - 8
Page 15
DBMS LAB
13
insert into emp values(7369, 'Smith','clerk',7902,'17-december-1980',800,NULL,20);
Output:
1 row inserted
insert into emp values(7499, 'Allen', 'salesman', 7698,'20-february-1981', 1600,300,30);
Output:
1 row inserted
insert into emp values(7521,'ward', 'salesman',7608, '22-february-1981', 1250,500,30);
Output:
1 row inserted
insert into emp values(7654, 'Martin', 'salesman',7698,'28-september-1981',1250,1400,30);
Output:
1 row inserted
insert into emp values(7844,'Turner','salesman',7698,'8-september-1981',1500,0,30);
Output:
1 row inserted
insert into emp values(7876,'Adams','clerk',7788,'13-july-1987', 1100, NULL, 20);
Output:
1 row inserted
insert into emp values(7900,'james','clerk',7698,'13-december-1981',950,NULL,30);
Output:
1 row inserted
insert into emp values(7934,'miller','clerk',7782,'21-march-1982',1300,NULL,10);
Output:
1 row inserted
Dispaly information of employee table
select* from emp;
Output:
Page 16
DBMS LAB
14
EMPNO EMPNAME JOB MGR HIREDATE SALARY
DNO
7839 king president - 17-NOV-81 5000
10
7698 blake manager 7839 01-MAY-81 2850
30
7782 clark manager 7839 09-JUN-81 2450
10
7902 ford analyst 7566 13-DEC-81 3000
20
7566 jones manager 7839 02-APR-81 2975
20
7788 Scott analyst 7566 13-JUL-87 3000
20
7369 Smith clerk 7902 17-DEC-80 800
20
7499 Allen salesman 7698 20-FEB-81 1600
30
7521 ward sales Man 7608 22-FEB-81 1250
30
7654 Martin sales man 7698 28-SEP-81 1250
30
7844 Turner salesman 7698 08-SEP-81 1500
30
7934 miller clerk 7782 21-MAR-82 1300
10
7876 Adams clerk 7788 13-JUL-87 1100
20
7900 james clerk 7698 13-DEC-81 950
30
Update row into a Department Table:
update dept
Set location =’Atlanta’
Where deptno=40;
Output:
ROWS UPDATED
Deletion of row into a Table
delete from emp
Where empno=7844;
Output:
STATEMENT PROCESSED
Alter Command
alter table dept add(NUM_OF_EMP int);
Output:
TABLE ALTERED
Drop Command
Page 17
DBMS LAB
15
drop table dept;
Output:
TABLE DROPPED
Creation Of Salgrade Table
create table salgrade(grade int,lowsal int,highsal int);
Output:
Table created
Insert Values into a salgrade Table
insert into salgrade values(1,700,1200);
Output:
1 row inserted
insert into salgrade values(2,1200,1400);
Output:
1 row inserted
insert into salgrade values(3,1400,2000);
Output:
1 row inserted
Description of salgrade table
desc salgrade;
Output:
Table
Colu
mn
Data
Type
Len
gth
Preci
sion
Sc
ale
Primar
y Key
Null
able
Def
ault
Com
ment
SALGRA
DE
GRA
DE
Numbe
r - - 0 -
- -
LOW
SAL
Numbe
r - - 0 -
- -
HIGH
SAL
Numbe
r - - 0 -
- -
1 - 3
Page 18
DBMS LAB
16
Display information of salgrade
Select * from salgrade;
Output:
GRADE LOWSAL HIGHSAL
1 700 1200
2 1200 1400
3 1400 2000
GRANT: Grant privileges to user using the GRANT statement.
session creation for user:
Permission given to user for create a table :
REVOKE: Revoke permissions using the REVOKE statement.
Remove given permission from user:
Page 19
DBMS LAB
17
Viva Questions:
1) What is SQL?
Structured Query Language SQL is a database tool that is used to create and access the
database to support software applications.
2) What are tables in SQL?
The table is a collection of record and its information at a single view.
3) What are the different types of statements supported by SQL?
4) Explain DML, DDL, DCL and TCL statements with examples?
DML: DML stands for Data Manipulation Language. DML is used to retrieve, store, modify,
delete, insert and update data in database.
Examples of DML statements: SELECT, UPDATE, INSERT, DELETE statements.
DDL: DDL stands for Data Definition Language. DDL is used to create and modify the
structure of database objects.
Examples: CREATE, ALTER, DROP statements.
DCL: DCL stands for Data Control Language. DCL is used to create roles, grant and revoke
permissions, establish referential integrity etc.
Examples: GRANT, REVOKE statements
TCL: TCL stands for Transactional Control Language. TCL is used to manage transactions
within a database.
Examples: COMMIT, ROLLBACK statements
5) What is the difference between Drop, Delete and Truncate statements in SQL
Server?
Drop, Delete and Truncate - All operations can be rolled back.
Delete is a logged operation, which means deleted rows are written to the transaction
log.Truncate is not a logged operation, which means deleted rows are not written to the
transaction log.
Hence, truncate is a little faster than Delete. You can have a where clause in Delete
statement where as Truncate statement cannot have a where clause. Truncate will delete all
Page 20
DBMS LAB
18
the rows in a Table, but the structure of the table remains. Drop would delete all the rows
including the structure of the Table.
6) What is Cascading referential integrity constraint?
Cascading referential integrity constraints allow you to define the actions Microsoft SQL
Server should take when a user attempts to delete or update a key to which an existing
foreign keys point.
You can instruct SQL Server to do the following:
a. No Action: This is the default behaviour. No Action specifies that if an attempt is made to
delete or update a row with a key referenced by foreign keys in existing rows in other tables,
an error is raised and the DELETE or UPDATE is rolled back.
b. Cascade: Specifies that if an attempt is made to delete or update a row with a key
referenced by foreign keys in existing rows in other tables, all rows containing those foreign
keys are also deleted or updated.
c. Set NULL: Specifies that if an attempt is made to delete or update a row with a key
referenced by foreign keys in existing rows in other tables, all rows containing those foreign
keys are set to NULL.
d. Set Default: Specifies that if an attempt is made to delete or update a row with a key
referenced by foreign keys in existing rows in other tables, all rows containing those foreign
keys are set to default values.
6) Why do we use SQL constraints? Which constraints we can use while creating a
database in SQL?
Constraints are used to set the rules for all records in the table. If any constraints get violated
then it can abort the action that caused it.
Constraints are defined while creating the database itself with the CREATE TABLE
statement or even after the table is created once with the ALTER TABLE statement.
There are 5 major constraints are used in SQL, such as NOT NULL: That indicates that the column must have some value and cannot be left
NULL.
UNIQUE: This constraint is used to ensure that each row and column has a unique
value and no value is being repeated in any other row or column.
PRIMARY KEY: This constraint is used in association with NOT NULL and
UNIQUE constraints such as on one or the combination of more than one column to
identify the particular record with a unique identity.
FOREIGN KEY: It is used to ensure the referential integrity of data in the table. It
matches the value in one table with another using the PRIMARY KEY.
CHECK: It ensures whether the value in columns fulfills the specified condition.
Page 21
DBMS LAB
19
EXPERIMENT-2
Aim: Simple queries: selection, projection, sorting on a simple table, Small-large number of
attributes ,Distinct output values ,Renaming attributes , Computed attributes Simple-complex
conditions (AND, OR, NOT).
Program:
1. Display the unique department with jobs
select unique dno,jobs from emp;
Output:
DNO JOB
10 Manager
30 SalesMan
20 Clerk
10 Clerk
30 Manager
20 Manager
10 President
20 Analyst
30 Clerk
2. Display the details of the clerk.
select * from emp
Where empname=’Clerk’;
Output:
EMP
NO
EMPNA
ME JOB
MG
R
HIREDA
TE
SALA
RY
CO
M
DN
O
ANNUALINC
OME
7782 Clark Manag
er 7839
09-JUN-
81 2450 - 10 29400
3. List all the clerks.
select empname from emp
where job='Clerk';
Page 22
DBMS LAB
20
Output:
EMPNAME
Adams
Smith
James
Miller
4. List all the employees join on may 1st 1981.
select empname from emp
where hiredate='01-May-1981';
Output:
EMPNAME
Blake
5. List the employees whose salaries are less than 3500
select empname from emp
where salary < 3500;
Output:
EMPNAME
Ward
Adams
Turner
Blake
Clark
Ford
Jones
Scott
Smith
Allen
Martin
James
Miller
Page 23
DBMS LAB
21
6. List the empno,empname,salary of all employees joined before 1st april 81.
select empno,empname,salary from emp
where hiredate <'01-April=1981';
Output:
EMPNO EMPNAME SALARY
7521 Ward 1250
7. List the employees whose experience is more than 10 years.
select empno,hiredate from emp
where (months_between(sysdate,hiredate))/12>10;
Output:
EMPNO HIREDATE
7521 22-FEB-81
7876 13-AUG-81
7844 08-SEP-81
7839 17-NOV-81
7698 01-MAY-81
7782 09-JUN-81
7902 13-DEC-81
7566 02-APR-81
7788 13-JUL-81
7369 17-DEC-81
7499 20-DEC-81
7654 28-SEP-81
7900 13-DEC-81
7934 21-MAR-82
8. List the employees working as manager.
select empno,empname,job from emp
Where job = ‘Manager’;
Output:
EMPNO EMPNAME JOB
7698 Blake Manager
7782 Clark Manager
Page 24
DBMS LAB
22
7566 Jones Manager
9. List the employes whose annual salary ranging from 23000 to 40000.
select empno,empname,salary from emp
where salary>23000 and salary<40000;
Output:
NO DATA FOUND
10. List the employees who joined in the year 1981 and who joined in month of January.
select empno,empname from emp
where hiredate>('01-Jan-81')and hiredate<('01-Jan-82');
Output:
EMPNO EMPNAME
7521 Ward
7876 Adams
7844 Turner
7839 King
7698 Blake
7782 Clark
7902 Ford
7566 Jones
7788 Scott
7369 Smith
7499 Allen
7654 Martin
7900 James
11. List the employees whose salary is 4 digit number.
select empname,salary from emp
where salary between 999 and 9999;
Output:
EMPNAME SALARY
Ward 1250
Adams 1100
Turner 1500
King 5000
Page 25
DBMS LAB
23
Blake 2850
Clark 2450
Ford 3000
Jones 2975
Scott 3000
Allen 1600
Martin 1250
Miller 1300
12. List the empno,empname,location,deptname of all the depts. of 10 or 20.
select empno,empname,location,dname from emp,depts
where depts.deptno=emp.dno and (deptno=10 or deptno=20);
Output:
EMPNO EMPNAME LOCATION DNAME
7876 Adams Dallas Research
7839 King NewYork Accounting
7782 Clark NewYork Accounting
7902 Ford Dallas Research
7566 Jones Dallas Research
7788 Scott Dallas Research
7369 Smith Dallas Research
7934 Miller NewYork Accounting
13. List the mgr of department 10 or 20.
select dno,mgr from emp
where dno=10 or dno=20;
Output:
DNO MGR
20 7788
10 -
10 7839
20 7566
20 7839
20 7566
20 7902
Page 26
DBMS LAB
24
10 7782
14. List the empno,empname,deptname of employees.
select empno,empname,dname
from emp,depts
where emp.dno=depts.deptno;
Output:
EMPNO EMPNAME DNAME
7521 Ward Sales
7876 Adams Research
7844 Turner Sales
7839 King Accounting
7698 Blake Sales
7782 Clark Accounting
7902 Ford Research
7566 Jones Research
7788 Scott Research
7369 Smith Research
7499 Allen Sales
7654 Martin Sales
7900 James Sales
7934 Miller Accounting
15.List the dname,location,empname from employee and department tables.
Select dname,location,empname
from emp,depts
Where depts..deptno=emp.dno;
Output:
DNAME LOCATION EMPNAME
Sales Chicago Ward
Research Dallas Adams
Sales Chicago Turner
Accounting NewYork King
Sales Chicago Blake
Page 27
DBMS LAB
25
Accounting NewYork Clark
Research Dallas Ford
Research Dallas Jones
Research Dallas Scott
Research Dallas Smith
Sales Chicago Allen
Sales Chicago Martin
Sales Chicago James
Accounting NewYork Miller
16. Display all the information of the employee table.
select * from emp;
Output:
EMP
NO
EMPNA
ME JOB
MG
R
HIREDA
TE
SALA
RY
CO
M
DN
O
ANNUALINC
OME
7521 Ward SalesM
an 7698
22-FEB-
81 1250 500 30 21000
7876 Adams Clerk 7788 13-AUG-
81 1100 - 20 13200
7844 Turner SalesM
an 7698 08-SEP-81 1500 0 30 18000
7839 King Preside
nt -
17-NOV-
81 5000 - 10 60000
7698 Blake Manag
er 7839
01-MAY-
81 2850 - 30 34200
7782 Clark Manag
er 7839
09-JUN-
81 2450 - 10 29400
7902 Ford Analys
t 7566
13-DEC-
81 3000 - 20 36000
7566 Jones Manag
er 7839
02-APR-
81 2975 - 20 35700
7788 Scott Analys
t 7566 13-JUL-81 3000 - 20 36000
7369 Smith Clerk 7902 17-DEC-
81 800 - 20 9600
7499 Allen SalesM
an 7698
20-DEC-
81 1600 300 30 22800
7654 Martin SalesM
an 7698 28-SEP-81 1250 1400 30 31800
7900 James Clerk 7698 13-DEC-
81 950 - 30 11400
Page 28
DBMS LAB
26
7934 Miller Clerk 7782 21-MAR-
82 1300 - 10 15600
17. Display unique jobs from employee table.
select unique job from emp;
Output:
JOB
Manager
Clerk
President
SalesMan
Analyst
18. List the employees who joined before 1981.
select empno,empname,hiredate from emp
where hiredate<('01-Jan-81');
Output:
EMPNO EMPNAME HIREDATE
7369 Smith 17-DEC-1980
19. List the empno,name,salary,experience of all employees working for mgr 7369.
select empno,empname,salary,(months_between(sysdate,hiredate))/12 from emp
where mgr =7369;
Output:
NO DATA FOUND
20. Display all the details of the employees whose comm is more than their salary.
select * from emp
where salary<com;
Output:
Page 29
DBMS LAB
27
EMP
NO
EMPNA
ME JOB
MG
R
HIREDA
TE
SALA
RY
CO
M
DN
O
ANNUALINC
OME
7654 Martin SalesM
an 7698 28-SEP-81 1250 1400 30 31800
21.List theemployees along with their exp & daily salary is more than 100.
select empname,(months_between(sysdate,hiredate)/12) exp,(salary/30) DS
from emp where (salary/30)>100;
Output:
EMPNA
ME EXP DS
King 39.29704431750298685782556750298
68578256
166.6666666666666666666666666666
66666667
22. List the employees who are working for department 10 or 20.
select empname,dno from emp
where dno=10 or dno=20;
Output:
EMPNAME DNO
Adams 20
King 10
Clark 10
Ford 20
Jones 20
Scott 20
Smith 20
Miller 10
23. List employees who joined in month of august 1980.
select empname from emp
where hiredate>=('01-Aug-1980') and hiredate<=('31-Aug-1980');
Output:
NO DATA FOUND
24. List employees whose annual salary ranging from 22000 to 45000.
Page 30
DBMS LAB
28
select empname,annualincome from emp
where annualincome<=22000 or annualincome>=45000;
Output:
EMPNAME ANNUALINCOME
Ward 21000
Adams 13200
Turner 18000
King 60000
Smith 9600
James 11400
Miller 15600
25.List the employees who joined in january.
Select * from emp whereto_char(hiredate,'Mon')='Jan';
Output:
EMPN
O
EMPNAM
E
JO
B
MG
R
HIREDAT
E
SALAR
Y
COM
M
DN
O
7934 miller clerk 7782 23-JAN-82 1300 - 10
26. List the employees who does not belongs to deptno 20.
select empno,empname from emp where dno!=20;
Output:
EMPNO EMPNAME
7893 Tim
7499 allen
7900 james
7934 miller
7698 blake
7782 clerk
7654 martin
7521 ward
7844 turter
Page 31
DBMS LAB
29
27. List employees who are working under manager.
select empno,empname from emp where job='manager';
Output:
EMPNO EMPNAME
7698 blake
7782 clerk
7566 jones
28. List all the clerks of deptno is 20
select empname from emp where empname = 'clerk' and dno=20;
Output:
no data found
29.List the employees whose deptno 30 or 10 joined in the year 1981.
selectempno,empname from emp
where to_char(hiredate,'YYYY')=1981 and dno = 10 or dno = 30;
Output:
EMPNO EMPNAME
7893 Tim
7499 allen
7900 james
7698 blake
7782 clerk
7654 martin
7521 ward
7844 turter
30. Display details of smith.
select * from emp where empname = 'smith';
Output:
EMPN
O
EMPNAM
E
JO
B
MG
R
HIREDAT
E
SALAR
Y
COM
M
DN
O
7369 smith clerk 7902 17-DEC-80 800 - 20
Page 32
DBMS LAB
30
31.Display location of smith.
select empno,empname,job,mgr,hiredate,salary,comm,dno,location from emp,dept
where dept.deptno=emp.dno and empname='smith';
Output:
EMP
NO
EMPNA
ME
JO
B
MG
R
HIREDA
TE
SALA
RY
COM
M
DN
O
LOCATI
ON
7369 smith cler
k 7902
17-DEC-
80 800 - 20 dallas
32. Displayempname,job who are without manager.
selectempno,empname,job from emp where job!='manager';
Output:
EMPNO EMPNAME JOB
7893 Tim President
7369 smith clerk
7499 allen salesman
7876 adams clerk
7900 james clerk
7934 miller clerk
7788 scott analyst
7654 martin salesman
7521 ward salesman
7844 turter salesman
33. List the emp whose salaries are odd value.
selectempname,salary from emp where mod(salary,2)=1;
Output:
EMPNAME SALARY
jones 2795
34. List the emp whose salary contain 3 digitno.
selectempno,empname from emp where salary<999;
Page 33
DBMS LAB
31
Output:
EMPNO EMPNAME
7369 smith
7900 james
35. List the amp who joined in the month of dec.
selectempno,empname from emp where to_char(hiredate,'Mon')='Dec';
Output:
EMPNO EMPNAME
7369 smith
7900 james
7788 scott
36. List the emp who joined before 15 th of month.
selectempname from emp where to_char(hiredate,'dd')='15';
Output:
no data found
37. Following output from emp ‘EMP-AND-JOB’ for emp and job
selectempname||'and'||job as "EMP_AND_JOB" from emp;
Output:
EMP_AND_JOB
Tim andPresident
smith andclerk
allenandsalesman
adamsandclerk
jamesandclerk
miller andclerk
blakeandmanager
clerk andmanager
scottandanalyst
Page 34
DBMS LAB
32
martin andsalesman
jones andmanager
ward andsalesman
turterandsalesman
38. List the employees in date in format of 9-JUN-81
selectempname from emp where hiredate = '09-JUN-81';
Output:
EMPNAME
clerk
39. Procedure for the following output for empclark and adams
selectempname ||'c'||(job)||')' as "emp(job)" from emp where empname = 'clark' and empname
= 'adams';
Output:
no data found
Viva questions:
1. What is CLAUSE?
SQL clause is defined to limit the result set by providing condition to the query. This usually
filters some rows from the whole set of records.
Example – Query that has WHERE condition
Query that has HAVING condition.
2. What is an ALIAS command?
ALIAS name can be given to a table or column. This alias name can be referred in WHERE
clause to identify the table or column.
Page 35
DBMS LAB
33
EXPERIMENT-3
Aim: Partial Matching operators (LIKE, %, _, *, ?) ,ASC-DESC ordering combinations
Checking for Nulls.
Programs:
1.Write a query to retrieve all employees who are joined during the 1987?
select empno,empname,hiredate
from emp
where hiredate like ‘%87’;
Output:
EMPNO EMPNAME HIREDATE
7788 SCOTT 13-JUL-1987
7876 ADAMS 13-JUL-1987
2.Find employee names start with A.
select empno,empname
from emp
where empname like 'A%';
Output:
EMPNO EMPNAME
7499 ALLEN
7876 ADAMS
3. Find employee names whose second letter start with A and after that any number of
letters.
select empno,empname
from emp
where empname like '_A%';
Page 36
DBMS LAB
34
Output:
EMPNO EMPNAME
7521 WARD
7654 MARTIN
7900 JAMES
4. Find the employee names and annual salary whose employee belongs to dept 10.
select empno,empname,deptno,salary*12 as annual sal
from emp
where deptno=10;
Output:
EMPNO EMPNAME DEPTNO
ANNUAL
SALARY
7839 KING 10 60000
7782 CLARK 10 29400
7934 MILLER 10 15600
5. Find employee names in ascending order whose deptno is 10.
select empno,empname,job,salary
from emp
where deptno=10
order by empname ASC;
Output:
EMPNO EMPNAME JOB SALARY
7782 CLARK MANAGER 2450
7839 KING PRESIDENT 5000
7934 MILLER CLERK 1300
6. Find employee salaries in descening order whose deptno=10.
Page 37
DBMS LAB
35
select empno,empname,job,salary
from emp
where deptno=10
order by salary desc;
Output:
EMPNO EMPNAME SALARY DEPTNO
7839 king 5000 president
7782 clark 2450 manager
7934 miller 1300 clerk
7. Find employee details whose comm is null.
select empname,comm
from emp
where comm is null;
Output:
EMPNO COMM
KING -
BLAKE -
CLARK -
JONES -
SCOTT -
FROD -
SMITH -
ADAMS -
JAMES -
MILLER -
8. Find the details of employee name must starts with ‘a’ and 4th character must be ‘e’
and ends with ‘n’.
select empno,empname
from emp
where empname like ‘A__e%n’;
Output:
Page 38
DBMS LAB
36
EMPNO EMPNAME
7499 ALLEN
9. Find details of employee whose name ends with ‘th’.
select empno,empname
from emp
where empname like ‘%th’;
Output:
EMPNO EMPNAME
7369 SMITH
10.Find the details of employee whose name can contain 3rd letter ‘i’.
select empno,empname
from emp
where empname like ‘__i%’;
Output:
EMPNO EMPNAME
7369 SMITH
Viva Questions:
1. Which operator is used in query for pattern matching?
LIKE operator is used for pattern matching, and it can be used as -.
1. % - Matches zero or more characters.
2. _(Underscore) – Matching exactly one character.
2. What is Query evaluation engine?
It executes low-level instruction generated by compiler.
3. What is DDL Interpreter?
It interprets DDL statements and record them in tables containing metadata.
Page 39
DBMS LAB
37
EXPERIMENT-4
Aim: Multi-table queries (JOIN OPERATIONS) ,Simple joins (no INNER JOIN) Aliasing
tables – Full/Partial name qualification ,Inner-joins (two and more (different) tables) ,Inner-
recursive-joins (joining to itself) ,Outer-joins (restrictions as part of the WHERE and ON
clauses) ,Using where & having clauses.
Program:
1.Find dept names of the employees
select e.empname,d,dname
from emp e,dept d
where e.dno=d.deptno;
Output:
EMPNAME DNAME
KING ACCOUNTING
BLAKE SALES
CLARK ACCOUNTING
JONES RESEARCH
SCOTT RESEARCH
FROD RESEARCH
SMITH RESEARCH
ALLEN SALES
WARD SALES
MARTIN SALES
TURNER SALES
ADAMS RESEARCH
JAMES SALES
MILLER ACCOUNTING
2. Find deptname of ALLEN.
select e.empname,d.dname
from emp e,dept d
where e.dno=d.deptno and empname=’allen’;
Output:
EMPNAME DNAME
ALLEN SALES
Page 40
DBMS LAB
38
3.Find the names of employees and deptno and their location where employee working
under dname sales.
select e.empno,e.empname,e.deptno,d.dname,d.location
from emp e,dept d
where e.dno=d.deptno and dname=’sales’;
Output:
EMPNO EMPNAME DEPTNO LOCATION DNAME
7698 BLAKE 30 CHICAGO SALES
7499 ALLEN 30 CHICAGO SALES
7521 WARD 30 CHICAGO SALES
7654 MARTIN 30 CHICAGO SALES
7844 TURNER 30 CHICAGO SALES
7900 JAMES 30 CHICAGO SALES
4.Find the empno,empname,dname whose employees belongs to the same department.
select empno,empname,dname,emp.deptno
from emp inner join dept
on emp.deptno=dept.deptno;
Output:
EMPNO EMPNAME DNAME DEPTNO
7566 jones research 20
7369 smith research 20
7499 allen sales 30
7521 ward sales 30
7654 martin sales 30
7934 miller accounting 10
7698 blake sales 30
7782 clark accounting 10
7788 scott research 20
7844 turner sales 30
7900 james sales 30
7839 king accounting 10
Page 41
DBMS LAB
39
7902 frod research 20
7876 adams research 20
5.Find the details of employees and dept whose dept numbers are not equals to each
other.
select empno,empname,job,emp.deptno,dname
from emp,dept
where emp.deptno!=dept.deptno;
Output:
EMPNO EMPNAME JOB DEPTNO DNAME
7499 allen salesman 30 research
7521 ward salesman 30 research
7654 martin salesman 30 research
7934 miller clerk 10 research
7698 blake manager 30 research
7782 clark manager 10 research
7844 turner salesman 30 research
7900 james clerk 30 research
7839 king president 10 research
7566 jones manager 20 operations
7369 smith clerk 20 operations
7499 allen salesman 30 operations
7521 ward salesman 30 operations
7654 martin salesman 30 operations
7934 miller clerk 10 operations
7698 blake manager 30 operations
7782 clark manager 10 operations
7788 scott analyst 20 operations
7844 turner salesman 30 operations
7900 james clerk 30 operations
7839 king president 10 operations
7902 frod analyst 20 operations
7876 adams clerk 20 operations
7566 jones manager 20 accounting
7369 smith clerk 20 accounting
7499 allen salesman 30 accounting
7521 ward salesman 30 accounting
7654 martin salesman 30 accounting
7698 blake manager 30 accounting
7788 scott analyst 20 accounting
Page 42
DBMS LAB
40
7844 turner salesman 30 accounting
7900 james clerk 30 accounting
7902 frod analyst 20 accounting
7876 adams clerk 20 accounting
7566 jones manager 20 sales
7369 smith clerk 20 sales
7934 miller clerk 10 sales
7782 clark manager 10 sales
7788 scott analyst 20 sales
7839 king president 10 sales
7902 frod analyst 20 sales
7876 adams clerk 20 sales
6.Find empnames,salaries and grades of employees whose deptno is 10.
Select e.ename,e.salary,A.grade
From emp e,salgrade A
Where e.sal between lowsalary and highsalary and deptno=10;
Output:
EMPNAME SALARY GRADE
MILLER 1300 2
7.Find empnames of each employee manager.
select e.empname||'works for'||m.empname
from emp e,emp m
where e.mgr=m.empno;
Output:
E.EMPNAME||'WORKSFOR'||M.EMPNAME
frod works forjones
scott works forjones
james works forblake
turner works forblake
Page 43
DBMS LAB
41
martin works forblake
ward works forblake
allen works forblake
miller works forclark
adams works forscott
clark works forking
blake works forking
jones works forking
smith works forfrod
8. Find the empno and deptname for the employees whose belons to deptno is 10 using
‘on’ clause.
select empno,dname,emp.deptno
from emp inner join dept
on emp.deptno=dept.deptno and emp.deptno=10;
Output:
EMPNO DNAME DEPTNO
7934 accounting 10
7782 accounting 10
7839 accounting 10
9. Display all employees and dname by using left outer join.
select empno,empname,dname
from emp left outer join dept
on emp.deptno=dept.deptno;
Output:
EMPNO EMPNAME DNAME
7876 adams Research
7902 frod Research
7788 scott Research
7369 smith Research
7566 jones Research
7839 king Accounting
7782 clark Accounting
7934 miller Accounting
Page 44
DBMS LAB
42
7900 james Sales
7844 turner Sales
7698 blake Sales
7654 martin Sales
7521 ward Sales
7499 allen Sales
10. Display all employees and dname by using right outer join.
select empno,empname,dname
from emp right outer join dept
on dept.deptno=emp.deptno;
Output:
EMPNO EMPNAME DNAME
7566 jones Research
7369 smith Research
7499 allen Sales
7521 ward Sales
7654 martin Sales
7934 miller Accounting
7698 blake Sales
7782 clark Accounting
7788 scott Research
7844 turner Sales
7900 james Sales
7839 king Accounting
7902 frod Research
7876 adams Research
- - Operations
Viva Questions:
1. What is a join?
This is a keyword used to query data from more tables based on the relationship between the
fields of the tables. Keys play a major role when JOINs are used.
2. What are the types of join and explain each?
Page 45
DBMS LAB
43
There are various types of join which can be used to retrieve data and it depends on the
relationship between tables.
Inner Join.
Inner join return rows when there is at least one match of rows between the tables.
Right Join.
Right join return rows which are common between the tables and all rows of Right hand side
table. Simply, it returns all the rows from the right hand side table even though there are no
matches in the left hand side table.
Left Join.
Left join return rows which are common between the tables and all rows of Left hand side
table. Simply, it returns all the rows from Left hand side table even though there are no
matches in the Right hand side table.
Full Join.
Full join return rows when there are matching rows in any one of the tables. This means, it
returns all the rows from the left hand side table and all the rows from the right hand side
table.
3. What is Self-Join?
Self-join is set to be query used to compare to itself. This is used to compare values in a
column with other values in the same column in the same table. ALIAS ES can be used for
the same table comparison.
4. What is Cross-Join?
Cross join defines as Cartesian product where number of rows in the first table multiplied by
number of rows in the second table. If suppose, WHERE clause is used in cross join then the
query will work like an INNER JOIN.
Page 46
DBMS LAB
44
EXPERIMENT-5
Aim: Nested queries :In, Not In Exists, Not Exists Dynamic relations (as part of SELECT,
FROM, and WHERE clauses).
Program:
1.Find the Nth (second) highest salary drawing employee details.
select empname,salary
from emp e1
where 1=(select count(distinct salary)
from emp e2
where e1.salary<e2.salary);
Output:
EMPNAME SALARY
scott 3000
frod 3000
2.List all employees who work in Chicago.
select empname,deptno,job
from emp
where deptno=(select deptno
from dept
where location='chicago');
Output:
EMPNAME DEPTNO JOB
allen 30 Salesman
ward 30 Salesman
martin 30 Salesman
blake 30 Manager
turner 30 Salesman
james 30 Clerk
Page 47
DBMS LAB
45
3. List out employees whose earning is above their manager’s salary.
select empno,empname,salary
from emp e1
where salary>(select salary
from emp e2
where e1.deptno=e2.deptno and e2.job='manager');
Output:
EMPNO EMPNAME SALARY
7788 scott 3000
7839 king 5000
7902 frod 3000
4. List employees with either same job as ‘Jones’ or the salary greater than that of
‘Ford’.
select empname,job
from emp
where job=(select job
from emp
where empname='jones' or salary>
(select salary
from emp
where empname='ford'));
Output:
EMPNAME JOB
Jones manager
Blake manager
Clark Manager
5. Display all the departments that have a minimum sal greater than that of department
20.
select deptno,min(salary)
Page 48
DBMS LAB
46
from emp
group by deptno
having min(salary)>(select min(salary)
from emp
where deptno=20);
Output:
DEPTNO MIN(SALARY)
30 950
10 1300
6. Find the job with lowest average salary
select job,avg(salary)
from emp
group by job
having avg(salary)=(select min(avg(salary))
from emp
group by job);
Output:
JOB AVG(SALARY)
clerk 1037.5
7. Find the employees who earn the same salary as the minimum salary for each
department.
select empname,salary ,deptno
from emp
where salary in(select min(salary)
from emp
group by deptno);
Output:
Page 49
DBMS LAB
47
EMPNAME SALARY DEPTNO
James 950 30
Smith 800 20
Miller 1300 10
8. Find the list of all employees who work for ‘Blakes’.
select empno,empname,job
from emp
where mgr=(select empno
from emp
where empname='blake');
Output:
EMPNO EMPNAME JOB
7499 allen salesman
7521 ward salesman
7654 martin Salesman
7844 turner Salesman
7900 james Clerk
9. Display all the employees who do not have any subordinates
select empname
from emp
where empno not in (select mgr
from emp
where mgr is not null);
Output:
EMPNAME
Turner
Ward
Martin
Allen
Miller
Smith
Page 50
DBMS LAB
48
adams
james
10. Find departments which are not in emp table
select *
from dept
where deptno not in (select deptno
from emp);
Output:
DEPTNO DNAME LOCATION
40 operations boston
11. Display the details of employees who are managed by the same manager and work
in the same department as the employees with empno in 7499or 7900.
select empno,mgr,deptno
from emp
where(mgr,deptno) in (select mgr,deptno
from emp
where empno in(7499,7900));
Output:
EMPNO MGR DEPTNO
7900 7698 30
7844 7698 30
7654 7698 30
7521 7698 30
7499 7698 30
12. Find the employees details from emp table such that the salary of employee
is greater than the average salary of his own department
select empno,empname,job,deptno
from emp e1
Page 51
DBMS LAB
49
where exists(select *
from emp e2
where e1.mgr=e2.empno);
Output:
EMPNO EMPNAME JOB DEPTNO
7566 jones manager 20
7369 smith clerk 20
7499 allen salesman 30
7521 ward salesman 30
7654 martin salesman 30
7934 miller clerk 10
7698 blake manager 30
7782 clark manager 10
7788 scott analyst 20
7844 turner salesman 30
7900 james clerk 30
7902 frod analyst 20
7876 adams clerk 20
13.Find all departments that do not have any employees.
select deptno,dname
from dept d
where not exists(select *
from emp e
where e.deptno=d.deptno);
Output:
DEPTNO DNAME
40 operations
Page 52
DBMS LAB
50
Viva Questions:
1. What is subquery?
A subquery is a query within another query. The outer query is called as main query, and
inner query is called subquery. SubQuery is always executed first, and the result of subquery
is passed on to the main query.
2. What are the types of subquery?
There are two types of subquery – Correlated and Non-Correlated.
A correlated subquery cannot be considered as independent query, but it can refer the column
in a table listed in the FROM the list of the main query.
A Non-Correlated sub query can be considered as independent query and the output of
subquery are substituted in the main query.
3. What is a nested table and how is it different from a normal table?
A nested table is a database collection object, which can be stored as a column in a table.
While creating a normal table, an entire nested table can be referenced in a single column.
Nested tables have only one column with no restriction of rows.
Page 53
DBMS LAB
51
EXPERIMENT-6
Aim: Set Oriented Operations :Union, Difference, Intersection, Division.
Program:
1. Using union display department numbers in emp and dept table.
select deptno
from emp
union
select dno
from dept;
Output
2.Find the common departments in employee and department table.
select deptno
from emp
intersect
select dno
from department;
Output :
3. Find the names of employees whose manager is 7698 and commission is null.
select ename
from emp
where mgr=7698
union
select ename
from emp
DNO
10
20
30
DNO
10
20
30
40
Page 54
DBMS LAB
52
where comm is null;
Output :
EMPNAME
Tim
adams
allen
blake
clerk
james
jones
martin
miller
scott
smith
turter
ward
4.Find all department in employee and department tables.
select deptno
from emp
unionall
select dno
from dept;
Output :
DNO
10
20
30
20
30
10
30
10
20
30
Page 55
DBMS LAB
53
20
30
30
30
40
20
10
5. Find the employees whose deptno is 20 but their salary is not greater than 2000
select ename,deptno
from emp
where deptno=20
minus
select ename,deptno
from emp
where sal<2000;
Output :
EMPNAME DNO
jones 20
scott 20
6. Using union matching select statement display deptno,location and hiredate of all
employees.
select dno,dloc,to_date(null) hiredate
from dept
union
select hiredate,deptno,to_char(null) dloc
from emp;
Output :
DEPTNO LOCATION HIREDATE
10 newyork -
10 - 09-JUN-81
10 - 17-NOV-81
10 - 23-JAN-82
20 dallas -
Page 56
DBMS LAB
54
20 - 17-DEC-80
20 - 12-APR-81
20 - 03-DEC-81
20 - 13-JUL-87
30 chicago -
30 - 20-FEB-81
30 - 22-FEB-81
30 - 01-MAY-81
30 - 08-SEP-81
30 - 28-SEP-81
30 - 13-DEC-81
40 boston -
7. Matching the select statement using union for the employee table.
select deptno,sal
from emp
union
select dno,0
from emp;
Output :
DNO SALARY
10 0
10 1300
10 2450
10 5000
20 0
20 800
20 1100
20 2795
20 3000
30 0
30 950
30 1250
30 1500
30 1600
30 2850
Page 57
DBMS LAB
55
Viva Questions:
1 ) Define UNION, MINUS, UNION ALL, INTERSECT?
MINUS – returns all distinct rows selected by the first query but not by the second.
UNION – returns all distinct rows selected by either query
UNION ALL – returns all rows selected by either query, including all duplicates.
INTERSECT – returns all distinct rows selected by both queries.
Page 58
DBMS LAB
56
EXPERIMENT-7
Aim: PL/SQL Programming I :Programs using named and unnamed blocks, Programs using
Cursors, Cursor loops and records.
Syntax of PL/SQL program:
Declare
Variable declaration;
Begin
Executable statements;
end;
PROGRAMS:
Unnamed blocks
1. Write a program to fetch salary from Emp table where empno is 7782
declare
num emp.empno%type;
salary emp.sal%type;
begin
select sal into salary from emp where empno=7782;
dbms_output.put_line('salary='||salary);
end ;
Output :
salary=2450
Statement processed.
2. Write a program using bind variable
variable g_sal NUMBER
begin
select sal into :g_sal from emp
where empno=7782;
end;
Output :
g_sal
----------
2450
3. Sum of salaries of all employees in specified department
Page 59
DBMS LAB
57
declare
sum_sal number(10,2);
dept_no number not null:=30;
begin
select sum(sal) into sum_sal
from emp where deptno=dept_no;
dbms_output.put_line('the sum salaryis'|| to_char(sum_sal));
end;
Output :
the sum salary is9400
Statement processed.
4. Write a program to calculate maximum of 2 salaries,fetch the salaries of any 2
employees and find the maximum salary.
declare
sal1 emp.sal%type;
sal2 emp.sal%type;
begin
select sal into sal1 from emp where empno=7698;
select sal into sal2 from emp where empno=7521;
if sal1>sal2 then
dbms_output.put_line('max salary='||sal1);
else
dbms_output.put_line('max salary='||sal2);
end if;
end;
Output :
max salary=2850
Statement processed.
5. Write a program to delete a row in a given table
declare
dept_no dept.deptno%type:=70;
begin
delete from dept where deptno=dept_no;
end;
Output :
1 row(s) deleted.
Page 60
DBMS LAB
58
6. Write a program using Case statement(like switch)
declare
grade char(1) := UPPER('&p_grade');
appraisal varchar2(20);
begin
appraisal:=case
when grade='A' then 'Excellent'
when grade='B' then 'very good'
when grade='C' then 'good'
else 'No such grade'
end;
dbms_output.put_line('Grade:'||grade||'Appraisal'||appraisal);
end;
Output :
Grade:A Appraisal Excellent
Statement processed.
ii.Programs using Cursors,Cursor loops Records,Record type
7. Write a program to fetch data from one table and keep it in a record and assign the
fetched data to another record.
declare
type deptrec is record
(no dept.deptno%type,name dept.dname%type,local dept.loc%type);
cursor c1 is select * from dept;
d deptrec;
begin
for drec in c1 loop
d.no:=drec.deptno;
d.name:=drec.dname;
d.local:=drec.loc;
dbms_output.put_line('dno'||''||'dname'||''||'loc');
dbms_output.put_line(d.no||''||d.name||''||d.local);
end loop;
end;
Output :
dno dname location
30 sales chicago
dno dname location
40 operating boston
dno dname location
Page 61
DBMS LAB
59
20 research dallas
dno dname location
10 accounting newyork
Statement processed.
8. Write a program to calculate the sum of sal and commission and if commission is
having NULL values prevent it in calculation using Record Concept. Fetch the data
based on empno.
declare
type emp2 is record
(num emp.empno%type,salary emp.sal%type,co emp.comm%type);
em emp2;
net number;
begin
select empno,sal,comm into em from emp where empno=7499;
net:=em.salary+nvl(em.co,0);
dbms_output.put_line('empno'||' '||'esal'||' '||'net');
dbms_output.put_line(em.num||' '||em.salary||' '||net);
exception
when no_data_found then
dbms_output.put_line('invalid empno');
end;
Output :
empno esalary net
7499 1600 1900
Statement processed.
9. Write a program to fetch the data from the department and store it in a PL/SQL
table and display it on the screen.
declare
cursor c1 is select * from dept;
type depttab is table of dept %rowtype
index by binary_integer;
dept_tab depttab;
i binary_integer:=0;
n number:=0;
begin
for deptrec in c1
loop
dept_tab(n):=deptrec;
n:=n+1;
end loop;
for i in 0.. n-1 loop
dbms_output.put_line(dept_tab(i).deptno||''||dept_tab(i).dname||''||dept_tab(i).loc);
Page 62
DBMS LAB
60
end loop;
end;
Output :
30 sales chicago
40 operating boston
20 research dallas
10 accounting newyork
Explicit cursor
10.Write a program to fetch all the date from a table and display it on the screen using
%row type attribute.
declare
cursor c1 is select * from dept;
drec c1%rowtype;
begin
open c1;
dbms_output.put_line('no'||' '||'Name'||' '||'LOC');
loop
fetch c1 into drec;
exit when c1%notfound;
dbms_output.put_line(drec.deptno||' '||drec.dname||' '||drec.loc);
end loop;
close c1;
end;
Output :
no Name LOCATION
30 sales chicago
40 operating boston
20 research dallas
10 accounting newyork
11. Write a program to display the details of employees in a specified deptno using
parameterized cursor.
declare
cursor c1(no in number) is select * from emp where deptno=no;
erec c1%rowtype;
begin
open c1(&no);
loop
fetch c1 into erec;
exit when c1%notfound;
Page 63
DBMS LAB
61
dbms_output.put_line('no='||erec.empno);
dbms_output.put_line('name='||erec.ename);
dbms_output.put_line('sal='||erec.sal);
dbms_output.put_line('job='||erec.job);
end loop;
close c1;
end;
Output :
no=7893
name=Tim
salary=5000
job=President
no=7934
name=miller
salary=1300
job=clerk
no=7782
name=clerk
salary=2450
job=manager
12. Write a program to display deptno, empno, ename from emp table using %Found
attribute.
declare
cursor c1 is select empno,ename,deptno from emp;
no emp.empno%type;
name emp.ename%type;
dno emp.deptno%type;
begin
open c1;
loop
fetch c1 into no,name,dno;
if(c1%found) then
dbms_output.put_line('no='||NO||' '||'name='||NAME||' '||'dno='||DNO);
else
exit;
end if;
end loop;
close c1;
end;
Output :
no=7893 name=Tim dno=10
no=7369 name=smith dno=20
no=7499 name=allen dno=30
no=7876 name=adams dno=20
no=7900 name=james dno=30
no=7934 name=miller dno=10
no=7698 name=blake dno=30
Page 64
DBMS LAB
62
no=7782 name=clerk dno=10
no=7788 name=scott dno=20
no=7654 name=martin dno=30
no=7566 name=jones dno=20
no=7521 name=ward dno=30
no=7844 name=turter dno=30
13. Write a program to find the number of records of any given table using %rowcount.
declare
cursor c1 is select * from emp;
erec c1%rowtype;
begin
open c1;
loop
fetch c1 into erec;
exit when c1%notfound;
end loop;
dbms_output.put_line('no of rows='||c1%rowcount);
close c1;
end;
Output :
no of rows=13
Statement processed.
14. Write a program to check whether the cursor is opened or not. If cursor is opened
“Display cursor already opened” else open the cursor and display the message “Just
Opened the cursor.”
declare
cursor c1 is select * from dept;
begin
open c1;
if(c1%isopen) then
dbms_output.put_line('cursor is already open');
else
open c1;
dbms_output.put_line('cursor is just opened');
end if;
close c1;
end;
Ouput :
cursor is already open
Statement processed.
Cursor loop
Page 65
DBMS LAB
63
15. Write a program to fetch all the data from salgrade table using cursor for loop.
declare
cursor c1 is select * from salgrade;
begin
for rec in c1 loop
dbms_output.put_line('grade'||' '||'hisal'||' '||'Losal');
dbms_output.put_line(rec.grade||' '||rec.hisal||' '||rec.losal);
end loop;
end;
Output :
grade highsalary Lowsalary
3 2000 1401
grade highsalary Lowsalary
1 1200 700
grade highsalary Lowsalary
4 3000 2001
grade highsalary Lowsalary
2 1400 1201
Viva Questions:
1) What is a Cursor?
A database Cursor is a control which enables traversal over the rows or records in the table.
This can be viewed as a pointer to one row in a set of rows. Cursor is very much useful for
traversing such as retrieval, addition and removal of database records.
2) What is PL/SQL?
PL/SQL (Procedural Language/SQL) is basically a procedural extension of Oracle – SQL.
PL/SQL helps the user to develop complex database applications using control structures,
procedures, functions, modules, etc.
3) Explain the purpose of %TYPE and %ROWTYPE data types with the example?
PL/SQL uses the %TYPE declaration attribute for anchoring. This attribute provides the
datatype of a variable, constant or column. %TYPE attribute is useful while declaring a
variable that has the same datatype as a table column.
For example, the variable m_empno has the same data type and size as the column empno in
table emp.
m_empno emp.empno%TYPE;
%ROWTYPE attribute is used to declare a variable to be a record having the same structure
as a row in a table. The row is defined as a record and its fields have the same names and data
types as the columns in the table or view.
For example: dept_rec dept%ROWTYPE;
This declares a record that can store an entire row for the DEPT table.
Page 66
DBMS LAB
64
4 ) What do you understand by PL/SQL packages?
PL/SQL packages are schema objects that group functions, stored procedures, cursors and
variables at one place.
Packages have 2 mandatory parts:
Package Specifications
Package body
5 ) What do you understand by PL/SQL cursors?
PL/SQL requires a special capability to retrieve and process more than one row and that
resource is known as Cursors. A cursor is a pointer to the context area, which is an area of
memory containing SQL statements and information for processing the statements.
PL/SQL Cursor is basically a mechanism under which multiple rows of the data from the
database are selected and then each row is individually processed inside a program.
6) Explain cursor types.
There are two types of cursors.
They are explained as follows:
a) Explicit Cursors: For queries that return more than one row, an explicit cursor is declared
and named by a programmer. In order to use explicit cursor in PL/SQL, 4 steps are followed
Declare the cursor Syntax: CURSOR<cursor_name>is SELECT statement;
Here, <cursor_name> is the name assigned to the cursor and SELECT statement is the query
that returns rows to the cursor active set.
Open the cursor Syntax: OPEN <cursor_nam>;
Where, <cursor_name> is the name of the previously defined cursor.
Fetch rows from the cursor
Syntax: FETCH <cursor_name> INTO <record_list>;
Here, <cursor_name> refers to the name of the previously defined cursor from which rows
are being fetched.
<record_list> represents the list of variables that will receive the data being fetched.
Closing the cursor Syntax: CLOSE <cursor_name>;
Here, <cursor_name> is the name of the cursor being closed.
b) Implicit cursors: When any SQL statement is executed, PL/SQL automatically creates a
cursor without defining such cursors are known as implicit cursors.
For the following statements, PL/SQL employs implicit cursors
INSERT
UPDATE
DELETE
SELECT ( queries that return exactly one row)
Page 67
DBMS LAB
65
7) What are actual parameters and formal parameters?
The variables or an expression referred to as parameters that appear in the procedure call
statement is known as Actual parameters.
For example: raise_sal(emp_num, merit+ amount);
Here in the above example, emp_num and amount are the two actual parameters.
The variables that are declared in the procedure header and are referenced in the procedure
body are called as Formal parameters.
For example:
PROCEDURE raise_sal( emp_id INTEGER) IS
curr_sal REAL:
………..
BEGIN
SELECT sal INTO cur_sal FROM emp WHERE empno = emp_id;
…….
END raise_sal;
Here in the above example, emp_id acts as a formal parameter.
Page 68
DBMS LAB
66
EXPERIMENT-8
Aim: PL/SQL Programming II :Creating stored procedures, functions
Programs:
1. Write a procedure to display ename,sal when user inputs empno using in/out
parameters.
create or replace procedure empdisp(no emp.empno%type) is name char(10);
salary number;
begin
select ename,sal into name,salary from emp where empno=no;
dbms_output.put_line('ename='||name||' '||'esal='||salary);
exception
when no_data_found then
dbms_output.put_line('Invalid empno');
end empdisp;
Output:
Procedure created.
SQL> exec empdisp(7369);
ename=SMITH esal=800
PL/SQL procedure successfully completed.
2. Write a procedure to update sal of Emp table taking empno as in parameter
create or replace procedure empset(no emp.empno%type,fsal emp.sal%type)is
isal emp.sal%type;
usal emp.sal%type;
begin
select sal into isal from emp where empno=no;
dbms_output.put_line('isal='||isal);
update emp set sal=fsal where empno=no;
select sal into usal from emp where empno=no;
dbms_output.put_line('usal='||usal);
end empset;
Output:
Procedure created.
SQL> exec empset(7369,1000);
isal=1000
usal=1000
PL/SQL procedure successfully completed.
Page 69
DBMS LAB
67
3. Write a function to check the validity of emp number from the Emp table.
create or replace function empvalid(no emp.empno%type)
return varchar2 is
emprec emp%rowtype;
begin
select * into emprec from emp where empno=no;
loop
if(emprec.empno=no) then
return('valid number');
end if;
end loop;
exception
when no_data_found then
return('invalid number');
end empvalid;
Output:
Function created. SQL>select empvalid(7369) from dual;
EMPVALID(7369) -----------------
VALID NUMBER
SQL>select empvalid(7777) from dual;
EMPVALID(7777) -----------------
INVALID NUMBER
4. Write a function, which returns Deptno when user inputs dname.
create or replace function dno(name dept.dname%type)
return
number is
no number;
begin
select deptno into no from dept where dname=name;
return(no);
exception
when no_data_found then
return(-999);
end dno;
Output:
Function created. SQL> select dno('SALES') from dual;
DNO('SALES')
------------ 30
Page 70
DBMS LAB
68
5. Create a function with a name insert_emp which is used to insert a record into the
emp table.
create or replace function insert_emp(no emp.empno%type,name emp.ename%type,salary
emp.sal%type,des emp.job%type)
begin
insert into emp(empno,ename,sal,job)
values(no,name,salary,des);
end insert_emp;
Output:
Function created
Exceptions
6. Write a program using exception whenever given deptno is not exist then create a
new department in the dept table.
declare
dept_no number;
begin
select deptno into dept_no from dept where dname='Delhi';
exception
when no_data_found then
insert into dept values(80,'Principal','Delhi');
end;
/
Output:
7. Write a program to get the salary of an employee
declare
vempno emp.empno%type;
vsal emp.sal%type;
Page 71
DBMS LAB
69
begin
vempno := 7499;
select sal into vsal from emp where empno = vempno;
dbms_output.put_line(‘salary = ‘ || vsal);
exception
when no_data_found then
dbms_output.put_line(‘employee not found…’);
end;
Output:
salary = 1600
Statement processed.
8. a)Check what happened when we input a 5 digit number.
b)Check what happens when we input employee number in single quotes.
c)Check what happens when we input alpha-numeric information.
d)Check what happens when there is a duplicate empno.
declare
vempno emp.empno%type;
vsal emp.sal%type;
begin
vempno := 7900;
select sal into vsal from emp where empno = vempno;
dbms_output.put_line(‘salary = ‘ || vsal);
exception
when no_data_found then
dbms_output.put_line(‘employee not found…’);
when others then
dbms_output.put_line(sqlcode || sqlcode);
end;
Output:
Salary = 950
Statement processed.
9. Creation of Packages
create or replace package samplepak
is
procedure proc1( n number, n1 out number);
function fun1(n number) return number;
end;
/
Output:
Package created.
Page 72
DBMS LAB
70
9.1. Creation of package body
create or replace package body samplepak
is
procedure proc1(n number, n1 out number)
is
begin
n1 := n * 5;
end proc1;
function fun1(n number) return number
is
n1 number;
begin
n1 := n * 2;
return n1;
end fun1;
end samplepak;
Output:
Package Body created
SQL> VARIABLE N NUMBER
SQL> EXECUTE SAMPLEPAK.PROC1(5,:N)
PL/SQL procedure successfully completed.
SQL> PRINT N
N
----------
25
SQL> EXECUTE :N := SAMPLEPAK.FUN1(4)
PL/SQL procedure successfully completed.
SQL> PRINT N
N
----------
8
9.2.Program to test Polymorphism
create or replace package body polypack
is
procedure proc1(n number, n1 out number)
is
Page 73
DBMS LAB
71
begin
n1 := n * 5;
end proc1;
procedure proc1(x varchar2,y varchar2, z out varchar2)
is
begin
z := concat(x,y);
end proc1;
end polypack;
/
Output:
SQL> VARIABLE N NUMBER
SQL> VARIABLE ST VARCHAR2(100)
SQL> EXECUTE POLYPACK.PROC1(5,:N)
PL/SQL procedure successfully completed.
SQL> PRINT N
N
----------
25
SQL> EXECUTE POLYPACK.PROC1('RAVI',' KIRAN',:ST)
PL/SQL procedure successfully completed.
SQL> PRINT ST
ST
------------------------------------------------------
RAVI KIRAN
Viva Questions:
1. What is a stored procedure?
Stored Procedure is a function consists of many SQL statement to access the database system.
Several SQL statements are consolidated into a stored procedure and execute them whenever
and wherever required.
Page 74
DBMS LAB
72
2. Advantages and Disadvantages of Stored Procedure?
Stored procedure can be used as a modular programming – means create once, store and call
for several times whenever required. This supports faster execution instead of executing
multiple queries. This reduces network traffic and provides better security to the data.
Disadvantage is that it can be executed only in the Database and utilizes more memory in the
database server.
3. What is recursive stored procedure?
A stored procedure which calls by itself until it reaches some boundary condition. This
recursive function or procedure helps programmers to use the same set of code any number of
times.
4. What do you understand by Exception handling in PL/SQL?
When an error occurs in PL/SQL, the exception is raised. In other words, to handle undesired
situations where PL/SQL scripts terminated unexpectedly, an error handling code is included
in the program. In PL/SQL, all exception handling code is placed in an EXCEPTION section.
There are 3 types of EXCEPTION:
Predefined Exceptions: Common errors with predefined names.
Undefined Exceptions: Less common errors with no predefined names.
User-defined Exceptions: Do not cause runtime error but violate business rules.
5. Enlist some predefined exceptions?
Some of the predefined exceptions are: NO_DATA_FOUND: Single row SELECT statement where no data is returned.
TOO_MANY_ROWS: Single row SELECT statement where more than one rows
are returned.
INVALID_CURSOR: Illegal cursor operation occurred.
ZERO_DIVIDE: Attempted to divide by zero.
6. What are the parameters that we can pass through a stored procedure?
We can pass IN, OUT & INOUT parameters through a stored procedure and they should be
defined while declaring the procedure itself.
7. What are the packages in PL SQL?
A package is a group of related database objects like stored procs, functions, types, triggers,
cursors, etc. that are stored in the Oracle database. It is a kind of library of related objects
which can be accessed by multiple applications if permitted.
PL/SQL Package structure consists of 2 parts: package specification & package body.
Page 75
DBMS LAB
73
EXPERIMENT-9
Aim: Triggers and auditing triggers
Program:
1. To create table level or statement triggers
create table client_master(clientno number(10),name varchar2(10),bal_due number(10,2),
address varchar2(10),city varchar2(10));
Output:
Table created
insert into client_master values(1000,'abc',10000,'hhh','kkk');
Output:
1 row(s) inserted
insert into client_master values(2000,'def',20000,'iii','lll');
Output:
1 row(s) inserted
insert into client_master values(3000,'ghi',30000,'jjj','mmm');
Output:
1 row(s) inserted
create table audit_client(clientno number(10),name varchar2(10),bal_due
number(10,2),operation varchar2(10),userid varchar2(10),odate date);
Output:
Table created
BEFORE UPDATE:
1 create or replace trigger audit_Trail
2 before update on client_master
3 for each row
4 declare
5 oper varchar2(10);
6 clientno client_master.clientno%type;
7 name client_master.name%type;
8 bal_due client_master.bal_due%type;
9 begin
10 if updating then
11 oper:='update';
12 end if;
13 if deleting then
14 oper:='delete';
Page 76
DBMS LAB
74
15 end if;
16 clientno:=:old.clientno;
17 name:=:old.name;
18 bal_due:=:old.bal_due;
19 insert into audit_client values(clientno,name,bal_due,oper,user,sysdate);
20 end;
Output :
Trigger created.
select * from client_master;
Output:
CLIENTNO NAME BAL_DUE ADDRESS CITY
1000 abc 10000 hhh kkk
3000 ghi 30000 Jjj mmm
2000 def 20000 Iii lll
update client_master
set bal_due=bal_due+100
where clientno=1000;
Output:
1 row(s) updated.
update client_master
set bal_due=bal_due+100
where clientno=2000;
Output:
1 row(s) updated.
update client_master
set bal_due=bal_due+100
where clientno=3000;
Output:
1 row(s) updated.
Page 77
DBMS LAB
75
select * from client_master;
Output:
CLIENTNO NAME BAL_DUE ADDRESS CITY
1000 abc 10100 hhh kkk
3000 ghi 30100 jjj mmm
2000 def 20100 iii lll
select * from audit_client;
Output:
CLIENTNO NAME BAL_DUE OPERATION USERID ODATE
1000 abc 10100 update ANONYMOUS 03-
MAR-21
2000 def 20100 update ANONYMOUS 03-
MAR-21
3000 ghi 30100 update ANONYMOUS 03-
MAR-21
AFTER DELETING :
create or replace trigger audit_Trail
after delete on client_master
for each row
declare
oper varchar2(10
clientno client_master.clientno%type;
name client_master.name%type;
bal_due client_master.bal_due%type;
begin
if updating then
oper:='update';
end if;
if deleting then
oper:='delete';
end if;
clientno:=:old.clientno;
name:=:old.name;
bal_due:=:old.bal_due;
insert into audit_client values(clientno,name,bal_due,oper,user,sysdate);
end;
Page 78
DBMS LAB
76
Output :
Trigger created.
select * from client_master;
Output :
CLIENTNO NAME BAL_DUE ADDRESS CITY
1000 abc 10100 hhh kkk
3000 ghi 30100 Jjj mmm
2000 def 20100 Iii lll
delete client_master
where clientno=1000;
Output:
1 row(s) deleted.
delete client_master
where clientno=3000;
output :
1 row(s) deleted.
select * from audit_client;
outptut:
CLIENTNO NAME BAL_DUE OPERATION USERID ODATE
1000 abc 10000 update ANONYMOUS 23-FEB-
21
2000 def 20000 update ANONYMOUS 23-FEB-
21
3000 ghi 30000 update ANONYMOUS 23-FEB-
21
1000 abc 10100 delete ANONYMOUS 23-FEB-
21
3000 ghi 30300 delete ANONYMOUS 23-FEB-
21
select * from client_master;
Output:
Page 79
DBMS LAB
77
CLIENTNO NAME BAL_DUE ADDRESS CITY
2000 def 20100 Iii lll
Viva Questions:
1. What is a Trigger?
The Trigger allows us to execute a batch of SQL code when table event occurs (INSERT,
UPDATE or DELETE commands are executed against a specific table).
2. Explain the difference in the execution of triggers and stored procedures?
A stored procedure is executed explicitly by issuing a procedure call statement from another
block via a procedure call with arguments.
The trigger is executed implicitly whenever any triggering event like the occurrence of DML
statements happens.
3. What is a trigger and what are its types?
A trigger is a stored program which is written in such a way that it gets executed
automatically when some event occurs. This event can be any DML or a DDL operation.
PL/SQL supports two types of triggers:
Row Level
Statement Level
Page 80
DBMS LAB
78
ADDITIONAL EXPERIMENTS
1.AIM: To Check whether a number is Armstrong or not using functions.
FUNCTION BODY:
set serveroutput on;
create or replace function armstrong(n number) return number is
r number(10);
a number(10);
b number(10);
c number(10);
begin
b:=0;
c:=n;
while(c>0)
loop
r:=c mod 10;
b:=b+(r*r*r);
c:=floor(c/10);
end loop;
return b;
end armstrong;
PROGRAM:
declare
n number(10);
m number(10);
o number(10);
begin
n:=&n;
o:=n;
m:=armstrong(n);
if(m=o) then
dbms_output.put_line('Given no is armstrong number');
else
dbms_output.put_line('Given no is not an armstrong
number');
end if;
end;
OUTPUT:
Enter value for n: 153
Given no is Armstrong number
PL/SQL procedure successfully completed.
Page 81
DBMS LAB
79
2. AIM: To Perform Banking Operations Using Procedures
TABLE:
create table acc(ac_no number(5), name varchar(20), balance number(6));
Table created.
insert into acc values(&ac_no,'&name',&balance);
select * from acc;
AC_NO NAME BALANCE
101 aaa 10000
102 bbb 6000
103 ccc 15000
104 ddd 5500
PROCEDURE DEFINITION:
set serveroutput on;
create or replace procedure withdraww (ac_no1 in number, amount1 in number) is
begin
update acc set balance=balance - amount1 where ac_no=ac_no1;
end;
create or replace procedure depositt (ac_no1 in number, amount1 in number) is
begin
update acc set balance=balance + amount1 where ac_no=ac_no1;
end;
PROGRAM:
set serveroutput on;
declare
choice number;
ac_no1 number(5);
amount number(5);
begin
ac_no1:= &ac_no1;
choice:= &choice;
amount:= &amount;
if choice=1 then
depositt(ac_no1,amount);
else
withdraww(ac_no1,amount);
end if;
end;
OUTPUT:
Enter value for ac_no1: 103
Enter value for choice: 1
Enter value for amount: 2000
PL/SQL procedure successfully completed.
Page 82
DBMS LAB
80
Enter value for ac_no1: 103
Enter value for choice: 2
Enter value for amount: 1000
PL/SQL procedure successfully completed.
select * from acc;
AC_NO NAME BALANCE
101 aaa 10000
102 bbb 6000
103 ccc 16000
104 ddd 5500