DBMS Lab Manual 2019-20
DBMS Lab Manual 2019-20
DBMS Lab Manual 2019-20
SUBJEC :__________________________________________________________________________________
C) Single-Row Functions
2. Prior Concepts:
1. Table
2. Where clause
3. New Concepts:
1. DML command
2. Constraints
4. Objectives:
1. Using SELECT command access the columns of the table.
2. Understand the use of SELECT command.
3. Implement the commands to restrict and sort the data.
4. Understand the use of Single Row functions.
5. Procedure:
1. Identify the required column for each table, its datatype and size.
2. Create table using CREATE command.
6. Implementation:
Done by students in the lab.
7. Results:
O/P of the program
8. Application:
Output:
Output:
Output:
Output:
Description:
1. Comparison Test (<,>, <=, >=, <>): It is used to compare data values.
6. Compound Search Condition(AND,OR,NOT): The AND and OR operators are used to filter records based
on more than one condition and The NOT operator displays a record if the condition(s) is NOT TRUE.
8. Order By [ASC|DESC]: it is use to sort result set in ascending order or descending order.
Syntax:
1. SELECT column_name(s) FROM table_name WHERE column_name (>, <, >=, <=, <>) value
2. SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2;
6. SELECT column1, column2, ... FROM <table_name> WHERE condition1 AND | OR condition2;
8. SELECT column1, column2, ... ,column n FROM <table_name> WHERE <condition> Order by
[ASC|DESC];
Questions:
Description:
Single Row functions - Single row functions are the one who work on single row and return one output per
row.
A) Character function:
a) CONCAT()
b) INITCAP()
c) LOWER()
d) UPPER()
e) SUBSTR()
B) Numeric Function:
a) ABS()
b) CEIL()
c) FLOOR()
d) ROUND()
e) TRUNC()
C) Date Function:
a) ADD_MONTHS()
b) CURRENT_DATE()
c) LAST_DAY()
d) MONTHS_BETWEEN()
e) SYSDATE()
f) NEXT_DAY()
Syntax:
Queries
1) Numeric Functions
a) select abs(-3) from dual
Output:
b) select ceil(-4.9) from dual
Output:
c) select floor(-4.9) from dual
Output:
d) select round(3/2) from dual
Output:
e) select trunc(16.738,1) from dual
Output:
2) Character Functions
a) select INITCAP(INFO) from help
Output:
b) select UPPER(INFO) from help
Output:
c) select LOWER(INFO) from help
Output:
d) select substr('Avirat',2,3) from dual
Output:
e) select concat('Avirat','Nimit') from dual
Output:
3) Date Functions
a) select SYSDATE from dual
Output:
b) select SYSDATE,ADD_MONTHS(SYSDATE,1) from dual
Output:
c) select SYSDATE,ADD_MONTHS(SYSDATE,-1) from dual
Output:
d) select SYSDATE,LAST_DAY(SYSDATE) from dual
Output:
e) select SYSDATE,NEXT_DAY(SYSDATE,'Monday') from dual
Output:
f) select MONTHS_BETWEEN ('01-JUL-2017','01-JUN-2017')from dual
Output:
Practical: 2
1. Title:
a) Displaying Data from Multiple Tables
b) Aggregating Data Using Group Functions
c) Sub queries
2. Prior Concepts:
1. Table
2. Aggregation
3. New Concepts:
1. Join operation
2. Group Functions
3. Sub query
4. Objectives:
1. Displaying data from multiple tables.
2. Aggregating data using group functions.
3. Implementation of sub queries.
5. Procedure:
1. Identify the required column from each table.
6. Implementation:
Done by students in the lab.
7. Results:
O/P of the program
8. Application:
Aim: Joining of emp and dept table using cross, Inner, Equi, Self and Outer Join.
Description:
1. SQL Joins clause is used to combine records from two or more tables in a database.
2. Types of Join:
a) CARTESIAN or NATURAL JOIN: Returns the Cartesian product of the sets of records from the two or
more joined tables.
b) INNER JOIN: Returns rows when there is a match in both tables.
c) EQUI JOIN: It performs a JOIN against equality or matching column(s) values of the associated tables.
An equal sign (=) is used as comparison operator.
d) SELF JOIN: It is used to join a table to itself as if the table were two tables, temporarily renaming at
least one table in the SQL statement.
e) Outer Join:
1. LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right
table.
2. RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records from the left
table.
3. FULL (OUTER) JOIN: Return all records when there is a match in either left or right table.
Syntax:
Example:
Syntax:
Ouput:
Syntax:
1. Cross Join
Syntax:
select * from emp11, dep11;
Output:
2. Inner Join
Syntax:
select state, dep11.id from emp11 inner join dep11 on emp11.id=dep11.id;
Output:
3. Equi Join
Syntax:
select * from emp11, dep11 where emp11.id=dep11.id;
Output:
4. Self Join
Syntax:
select e.id as employeeid, e1.state as employeestate from emp11 e, emp11 e1 where e1.state=e.state;
Output:
5. Left Outer Join
Syntax:
select * from emp11 left join dep11 on emp11.id=dep11.id;
Output:
Aim: Use of aggregate functions and Group by clause in SQL Select Statement
Description:
Aggregate function: Aggregate functions perform a summary operation on all the values that a query
returns.
Syntax:
Group by : The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM,
AVG) to group the result-set by one or more columns.
Order by: To put the result in specific order either in ascending or descending order.
Syntax:
Example:
Table: Foodcart
Food Sold
Pizza 349
Hotdog 500
Pizza 70
3. Subqueries
Aim: Write subquery using comparison operator, IN operator, Exist operator and ANY & ALL.
Description:
2. Subquery Set Membership Test(IN): It is used to check the value of an expression with a set of
values produced by a subquery.
3. Existence Test(Exists): It is used to tests whether subquery produces any of query results.
4. Qualified Comparision Test(ANY or ALL): It is used to compare the value of an expression with
each of the set value produces by subquery.
Syntax:
Example :
select empno, ename, job, sal from Empl where job IN (select job from emp where sal>2000);
Syntax: select topic,seq from help where seq=(select min(seq) from help)
Syntax: select info,seq from help where seq=(select max(seq) from help)
3. Display topic and sequence from help for less than total number of sequence.
Syntax: select topic,seq from help where seq<(select count(seq) from help)
4. Display the topic and sequence from help table for sequences having value greater than minimum
value.
Syntax: select topic,seq from help where seq>(select min(seq) from help)
Practical: 3
2. Prior Concepts:
1. Table
3. New Concepts:
1. Insert Command
2. Update Command
3. Delete Command
4. Objectives:
5. Procedure:
6. Implementation:
6. Results:
8. Application:
Description: The INSERT INTO statement is used to insert new records in a table.
Syntax:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
Or
Example:
Questions to practice:
Create following table and insert at least 5 rows in each using insert syntax.
Description: The UPDATE and SET statement is used to update records in a table.
Example:
Questions to practice:
Description: The DELETE statement is used to delete one or more records in a table.
Example:
3. New Concepts:
1. Constraints
2. Keys
4. Objectives:
1. Using CREATE command create a table.
2. Assign datatype and size to the column.
3. Understand the use of various keys.
4. Implement the required constraint on it.
5. Procedure:
1. Identify the required column for each table, its datatype and size.
2. Create table using CREATE command.
6. Implementation :
Done by students in the lab.
7. Results:
O/P of the program
8. Application:
Creating Database
v. Renaming table
change the table name customers to customer info
rename customers to customerinfo;
PRIMARY CONSTRAIN
UNIQUE CONSTRAINT
Description : Used to store client’s orders with details of each product ordered.
3. New Concepts:
1. Views
2. Database Objects
3. Controlling User Access
4. Objectives:
1. Creating Views and perform manipulation
2. Creating database objects
3. Making Use of GRANT and REVOKE command
5. Procedure:
1. Create a table and make a view on it.
2. Perform INSERT,DELETE and UPDATE operation on VIEWS.
3. Create two user and allow them to share table using GRANT and REVOKE command.
6. Implementation :
Done by students in the lab.
7. Results:
O/P of the program
8. Application:
Creating Views, database object and using GRANT and REVOKE command.
a. Creating Views
i. create view for train table with train_no and train_name columns.
Output:
SEQUENCES
ii. Insert the records into passenger through sequences including nextval() function.
Create user
connect system/tiger;
grant create table to shweta;
connect shweta/shweta123;
connect system/tiger;
REVOKING
connect shweta/shweta123;
revoke select on student from nita;
Output:
Practical: 6
1. Title:
Using SET operators, Date/Time Functions, GROUP BY clause (advancedfeatures) and advanced subqueries.
2. Prior Concepts:
1. Operators
2. Function
3. Queries
3. New Concepts:
1. Set Opeartors
3. Date/Time Functions
4. Group By clause (advanced subqueries)
4. Objectives:
1. Performing SET operators
2. Using date and time function
3. Getting output by firing advanced subqueries
5. Procedure:
1. Create a table and perform set operation on it.
2. Use date and time function to find current date, time, month, number of days etc
3. Execute different types of subqueries.
6. Implementation:
Done by students in the lab.
7. Results:
O/P of the program
8. Application:
MINUS
To find the names of the passenger who are travelling to Kolkata except those who are travelling on
02/02/2014
INTERSECT
To find the id of the passenger who are travelling on 01/06/2016 and going to Kolkata
Output:
b. Datetime Functions
i. Get the current system date.
select sysdate from dual;
ii. To get the date of next wedesday after the passenger has travelled.
iv. Use trunc function to truncate the date to year,month and day.
v. Get the total numbers of days passed after the passenger has travelled
select journey_id,round(sysdate-date_journey) as days_after_travelling from journey;
vi. Get the number of months passed since the passenger has travelled.
iii. To get the current time zone value set for the session.
select sessiontimezone from dual;
iv. To get the current time zone value set for the database.
select dbtimezone from dual;
Output:
TIME FUNCTION
c. GROUP BY CLAUSE
To find the coach no in which maximum number of passenger travels.
select max(total_passenger) from (select count(pid) as total_passenger from ticket group by coach_no);
__________________________________________________________________________________________
________OUTPUT
d. ADVANCED SUBQUERIES
i. PAIRWISE SUBQUERY
Get the pid of the passenger who have the same coach no and class.
__________________________________________________________________________________________
________OUTPUT
Practical: 7
1.Title:
PL/SQL Basics
2. Prior Concepts:
SQL basic Commands
3. New Concepts:
1. Declaring Variables :
In PL/SQL, a variable is a meaningful name of a temporary storage location that supports a particular data
type in a program. Before using a variable, you need to declare it first in the declaration section of a PL/SQL
block
Syntax:
DECLARE
Variables declarations
BEGIN
SELECT <select_list> INTO <variable_list> FROM <table_name> WHERE <condition>
EXCEPTION
Error handling code
END
Syntax:
IF <Condition> THEN
<Action>
ELSIF <Condition> THEN
<Action>
ELSE
<Action>
END IF;
4. Objectives:
5. Understand the declaration of variables in PL/SQL blocks
6. Understand select statement in PL/SQL blocks
7. Understand the control structures in PL/SQL.
5. Procedure:
1. Declare variables in PL/SQL block
2. Write select statement in PL/SQL block
3. Implement if condition ,for loop, while loop
6. Implementation :
Done by students in the lab.
7. Results:
O/P of the PL/SQL block
8. Application:
PL/SQL block
9. Questions:
a) Declaring variables
1)
declare
i int:=10;
j int:=20;
begin
DBMS_OUTPUT.PUT_LINE('value of i=' || (i));
DBMS_OUTPUT.PUT_LINE('value of j=' || (j));
end;
o/p:
value of i=10
value of j=20
PL/SQL procedure successfully completed.
2)
declare
i int:= 5;
j int:=10;
k int := i + j;
begin
DBMS_OUTPUT.PUT_LINE('value of k=' || (k));
end;
o/p:
value of k=15
PL/SQL procedure successfully completed.
3)declare
i int:=10;
j int:=5;
k int;
begin
k:=i + j;
DBMS_OUTPUT.PUT_LINE('value of k=' || (k));
k:= i - j;
DBMS_OUTPUT.PUT_LINE('value of k=' || (k));
k:= i *j;
DBMS_OUTPUT.PUT_LINE('value of k=' || (k));
k := i/j;
DBMS_OUTPUT.PUT_LINE('value of k=' || (k));
end;
o/p:
value of k=15
value of k=5
value of k=50
value of k=2
PL/SQL procedure successfully completed.
end;
o/p:
Salary=90000
c)Interacting with Oracle serever
declare
i int;
j int;
sum int;
begin
i:=&i;
j:=&j;
sum:=i+j;
DBMS_OUTPUT.PUT_LINE(‘Answer=’ || (sum));
end;
o/p:
Enter value for i=10
Enter value for j=20
Answer=30
i)Using if statements
declare
a int:=5;
b int:=6;
begin
if a < b then
DBMS_OUTPUT.PUT_LINE(a);
end if;
end;
o/p:
5
declare
a int;
b int;
begin
a:=&a;
b:=&b;
if a < b then
DBMS_OUTPUT.PUT_LINE(a);
else
DBMS_OUTPUT.PUT_LINE(b);
end if;
end;
o/p:
Enter value for a: 10
old 5: a:=&a;
new 5: a:=10;
Enter value for b: 20
old 6: b:=&b;
new 6: b:=20;
10
declare
per number;
begin
per:=&per;
if per>=75 then
DBMS_OUTPUT.PUT_LINE('Your grade: A');
else
DBMS_OUTPUT.PUT_LINE('Your grade: F');
end if;
end;
o/p;
Enter value for per: 65
old 4: per:=&per;
new 4: per:=65;
Your grade: B
iv)Using CASE-WHEN
declare
per number:=&per;
begin
case per
when 8 then DBMS_OUTPUT.PUT_LINE('Your grade: A');
when 7 then DBMS_OUTPUT.PUT_LINE('Your grade: B');
when 6 then DBMS_OUTPUT.PUT_LINE('Your grade: C');
when 5 then DBMS_OUTPUT.PUT_LINE('Your grade: D');
else DBMS_OUTPUT.PUT_LINE('Your grade: F');
end case;
end;
/
iv)Using CASE-WHEN
declare
per number:=&per;
begin
case per
when 8 then DBMS_OUTPUT.PUT_LINE('Your grade: A');
when 7 then DBMS_OUTPUT.PUT_LINE('Your grade: B');
when 6 then DBMS_OUTPUT.PUT_LINE('Your grade: C');
when 5 then DBMS_OUTPUT.PUT_LINE('Your grade: D');
else DBMS_OUTPUT.PUT_LINE('Your grade: F');
end case;
end;
/
o/p:
Enter value for per: 8
old 2: per number:=&per;
new 2: per number:=8;
Your grade: A
PL/SQL procedure successfully completed.
declare
a int:= 0;
begin
while a < 5
loop
a := a + 1;
DBMS_OUTPUT.PUT_LINE( a);
end loop;
end;
o/p:
1
2
3
4
5
Vi)FOR Loop
begin
for i in 1..5
loop
dbms_output.put_line (i);
end loop;
end;
o/p:
1
2
3
4
5
begin
for i in reverse 1..5
loop
dbms_output.put_line (i);
end loop;
end;
o/p:
5
4
3
2
1
Practical: 8
1. Title:
Working with Composite Data Types
2. Prior Concepts:
Explicit cursors are programmer-defined cursors for gaining more control over the context area. An
explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row.
Cursor involve following four steps:
1. Declaring the Cursor
2. Opening the Cursor
3. Fetching the Cursor
4. Closing the Cursor
c. Handling Exceptions
Exception is a runtime error or warning condition, which can be predefined or user defined. Or it could be
condition that can change execution flow and can cause application into inconsistent state.
Types:
1. Unnamed system exception : There are two ways to handle unnamed sysyem exceptions:
i. By using the WHEN OTHERS exception handler, or
ii. By associating the exception code to a name and using it as a named exception.
We can assign a name to unnamed system exceptions using a Pragma called
EXCEPTION_INIT.EXCEPTION_INIT will associate a predefined Oracle error number to a
programmer_defined exception name.
2. Named system exception: System exceptions are automatically raised by Oracle, when a program
violates a RDBMS rule.
Named system exceptions are:
1) Not Declared explicitly,
2) Raised implicitly when a predefined Oracle error occurs,
3) caught by referencing the standard name within an exception-handling routine.
3. User defined exception: Apart from system exceptions we can explicitly define exceptions based on
business rules. These are known as user-defined exceptions.
4. Objectives:
1. Understand Composite Data Types
2. To understand Cursors
3. To implement Exception Handlimg
5. Procedure:
1. Write a PL/SQL block
2. Implement Composite Data Types
3. Implement Cursor
-Declaring the Cursor
-Opening the Cursor
-Fetching the Cursor
-Closing the Cursor
6. Implementation:
Done by students in the lab
7. Results:
O/P of PL/SQL block.
8. Application:
-Errors can be handled by Exception handling
9. Questions:
declare
type nametype is table of varchar2(20) index by binary_integer;
cursor namecur is select ename from emp2 where eid=&eid;
cnt NUMBER(3):=0;
i number(3):=0;
namerec nametype;
begin
for mrec in namecur
loop
namerec(i):=mrec.ename;
i:=i+1;
end loop;
cnt:=i-1;
for j in 0..cnt
loop
dbms_output.put_line(' Employee name '||to_char(j+1)||' '||namerec(j));
end loop;
end;
/
%ROWTYPE
DECLARE
x emp2%ROWTYPE;
BEGIN
SELECT * INTO x FROM emp2 WHERE sal=20000;
DBMS_OUTPUT.PUT_LINE('id = ' || x.eid);
DBMS_OUTPUT.PUT_LINE('Name = ' || x.ename);
DBMS_OUTPUT.PUT_LINE('Salary = ' || x.sal);
END;
eid ename
1 a
2 b
3 c
1)
declare
type abc is record
(
x int,
y char(10)
);
p abc;
begin
select eid,ename into p from e2 where esal=40000;
insert into e1 values(p.x,p.y);
end;
eid ename
1 a
2 b
3 c
4 d
1 Neha 10000 HR
3 Nilesh 90000 HR
5 rahul 50000 HR
6 Pooja 90000 Admin
7 Nita 80000 HR
o/p:
table created
declare
cursor c1 is select * from emp;
x emp%rowtype;
begin
open c1;
fetch c1 into x;
insert into emp_cursor values(x.eid,x.ename,x.sal,x.dept);
close c1;
end;
o/p
Statement Processed
o/p:
declare
cursor c1 is select * from emp;
x emp%rowtype;
begin
open c1;
for i in 2..4
loop
fetch c1 into x;
insert into emp_cursor values(x.eid,x.ename,x.sal,x.dept);
end loop;
close c1;
end;
c)Handling Exceptions
SQL>declare
x number:=1;
y number:=0;
z number;
begin
z:=x/y;
insert into temp values(z,'zero divide');
end;
/
SQL>declare
x number:=1;
y number:=0;
z number;
begin
z:=x/y;
insert into temp values(z,'zero divide');
exception when zero_divide then
insert into temp values(0,'zero divide error');
end;
/
o/p:
PL/SQL Procedure Successfully completed
id value
o zero divide error
SQL>declare
x number:=10;
y number:=5;
z number;
begin
z:=x/y;
insert into temp values(z,'zero divide');
exception when zero_divide then
insert into temp values(0,'zero divide error');
end;
/
o/p:
PL/SQL Procedure Successfully completed
id value
o zero divide error
2 zero divide
2)The VALUE_ERROR Exception
SQL>declare
x char(4);
begin
x:='Too big';
insert into temp values(1,x);
exception when value_error then
insert into temp values(0,'value error');
end;
/
o/p:
PL/SQL Procedure Successfully completed
id value
o zero divide error
2 zero divide
o value error
SQL>declare
x char(4);
begin
x:='Too';
insert into temp values(1,x);
exception when value_error then
insert into temp values(0,'value error');
end;
/
o/p:
PL/SQL Procedure Successfully completed
SQL>declare
x number;
begin
select eid into x from emp where ename='no name';
insert into temp values(x,'Hello');
exception when no_data_found then
insert into temp values(0,'data error');
end;
/
o/p:
PL/SQL Procedure Successfully completed
id value
o zero divide error
2 zero divide
0 value error
1 Too
0 data error
SQL>declare
x number;
begin
select eid into x from emp where ename='priya';
insert into temp values(x,'Hello');
exception when no_data_found then
insert into temp values(5,'data error');
end;
/
o/p:
PL/SQL Procedure Successfully completed
select * from temp;
o/p:
id value
o zero divide error
2 zero divide
0 value error
1 Too
0 data error
3 Hello
Practical: 9
2. Prior Concepts:
Concepts of PL/SQL block
3. New Concepts:
Procedure and Function
A Procedure or Function is a logically grouped set of SQL and PL/SQL statements that perform a specific
task.
A stored procedure or function is a named PL/SQL code block that has been complied and stored in one
of the Oracle engine’s system tables
Package:
A package is a collection of stored functions, procedures and exceptions.
A package is compiled and stored in database as an object.
A package comprises 2 parts:
1)A specification : It contains the list of various functions/procedure names which will be a part of the
package.
2)A body : This contains the actual PL/SQL code implementing the logics of functions and procedures
declared in “specification”.
4. Objectives:
-Understand the use of Procedure and Function
-Implement Procedure and Functions in PL/SQL block.
-Understand use of packages in PL/SQL block
5. Procedure:
-Declare a PL/SQL block
-Write Procedure in PL/SQL block
-Call Procedure in other PL/SQL block
6. Implementation:
Done by students in the lab
7. Results:
O/P of program
8. Application:
-To display the salary of employee procedure or function can be created
9. Questions:
1.Write a procedure to add two numbers and call that procedure through the PL/SQL block
sql>set serveroutput on
sql>ed d:\f1.sql
CREATE OR REPLACE PROCEDURE ADD_TWO_NOS
IS
A NUMBER(3):=10;
B NUMBER(3):=20;
C NUMBER(5);
BEGIN\
C:=A+B;
DBMS_OUTPUT.PUT_LINE('SUM OF ' || A || ' AND ' || B || ' IS ' || C);
END;
/
o/p:
procedure created
sql>ed d:\f2.sql
BEGIN
ADD_TWO_NOS;
END;
/
sql>@ d:\f2.sql
2.Write a function to add two numbers and call that function through the PL/SQL block
sql>set serveroutput on
sql>ed d:\fun1.sql
o/p:
function created
sql>ed d:\fun2.sql
DECLARE
X NUMBER(3);
Y NUMBER(3);
Z NUMBER(3);
BEGIN
X:=&X;
Y:=&Y;
Z:=ADD_TWO_NOS1(X,Y);
DBMS_OUTPUT.PUT_LINE('VALUE OF Z IS '||Z);
END;
/
sql>@ d:\fun2.sql
Practical: 10
1.Title: Creating Database Triggers.
2. Prior Concepts:
Concepts of PL/SQL block ,basic DML commands
3. New Concepts:
Triggers are stored programs, which are automatically executed or fired when some events occur.
Component of Trigger:
Types of Trigger:
1. DDL Trigger: It allows you to event to fire on DDL commands (Schema-Level commands like
LOGIN_USER, CREATE, ALTER etc.).
2. DML Trigger: This triggers define on the table level DML commands like INSERT, UPDATE or DELETE.
Syntax:
ON {[schema_name.]SCHEMA|DATABASE}
BEGIN
END
[OF col_name]
ON table_name
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
4. Objectives:
Understand the concept of Triggers
5. Procedure:
-Create PL/SQL block
-Write Trigger statements
6. Implementation:
Done by students in the lab
7. Results:
O/P of PL/SQL block
8. Application:
-To store the records of employees who have the organization.
-To reduce the number of items when purchased by any customer
9. Questions:
1 Neha 10000 HR
2 Priya 20000 HR
3 Nilesh 90000 HR
4 Nila 40000 sales
5 rahul 50000 HR
6 Pooja 90000 Admin
7 Nita 80000 HR
o/p:
o/p:
1 Neha 10000
2 Priya 20000
3 Nilesh 90000
4 Nila 40000
5 rahul 50000
6 Pooja 90000
7 Nita 80000
2 Priya 20000