DBMS Lab Manual 2019-20

Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

LAB MANUAL

SUBJEC :__________________________________________________________________________________

YEAR : ______________________ SEMESTER :______________________________________

ACADEMIC YEAR : _________________________________________________________________________


Practical: 1
1. Title:
A) Writing Basic SQL SELECT Statements

B) Restricting and Sorting Data

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:

A) Writing basic SQL SELECT statements.


Aim: Writing the basic SQL select statements.
Description: SELECT Statement
 The SQL SELECT statement is DML command used to fetch the data from a database table which
returns this data in the form of a result table. These result tables are called result-sets.
 It allows you to select multiple tuples (Row) or field (Columns) from relation (Table).
 The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by
joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from
the table. You should use the WHERE clause to filter the records and fetching only the necessary
records.
 Syntax : SELECT column1, column2, column n FROM table name [WHERE <Condition>];
Questions:

1) Display details of help table.

Syntax: Select * from help

Output:

2) Display info from help table.

Syntax: Select info from help;

Output:

3) Display seq and info of help whose topic is accept.

Syntax: Select seq,info from help where topic ='ACCEPT';

Output:

4) Display details of help whose topic is change.

Syntax: Select * from help where topic='CHANGE'

Output:

B) Restricting and Sorting Data

Aim: Displaying data with restricted row and sorted order.

Description:

1. Comparison Test (<,>, <=, >=, <>): It is used to compare data values.

2. Range Test (Between): It is use to search value in given range.

3. Set Membership Test (IN): It is use to search value in specified set.

4. Pattern Matching (LIKE): It is used to search specified pattern.

 % : The percent sign represents zero, one, or multiple characters

 _ : The underscore represents a single character

5. Null Value Test (Is Null): It is used to search null value.

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.

7. Concatenating Data Columns: “||” is used to combine columns of select statement.

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;

3. SELECT column_name(s) FROM table_name WHERE column_name IN (value1, value2, ...);

4. SELECT column1, column2, ...FROM <table_name> WHERE column LIKE pattern;

5. SELECT column_names FROM <table_name> WHERE column_name IS NULL;

6. SELECT column1, column2, ... FROM <table_name> WHERE condition1 AND | OR condition2;

7. SELECT column1||column2 , ... ,column n FROM <table_name> WHERE <condition>;

8. SELECT column1, column2, ... ,column n FROM <table_name> WHERE <condition> Order by
[ASC|DESC];

Questions:

1. Display details of help whose topic is accept and seq is 7.


Syntax: Select * from help where topic='ACCEPT' and seq=7;
Output:

2. Display details of help whose topic is accept or change.


Syntax: Select * from help where topic='ACCEPT' OR TOPIC='CHANGE';
Output:

3. Display details of help whose topic is break or change or attribute.


Syntax: Select * from help where topic IN('BREAK','CHANGE','ATTRIBUTE');
Output:

4. Display details of help whose seq between 4 to 9.


Syntax: Select * from help where seq between 4 and 9;
Output:

5. Display details of help whose seq between 1 to 3 of topic @.


Syntax: Select * from help where seq between 1 and 3 and topic='@';
Output:

6. Display details of help in ascending order.


Syntax: Select * from help order by topic asc;
Output:

7. Display details of help in descending order.


Syntax: Select * from help order by topic desc;
Output:

8. Display details of help table whose info starts with R.


Syntax: Select * from help where info like 'R%';
Output:
9. Display details of help table whose info ends with e.
Syntax: Select * from help where info like '%e';
Output:

C) Single Row Functions:

Aim: Using of single row function in Select statement.

Description:

Single Row functions - Single row functions are the one who work on single row and return one output per
row.

Single row function has following types:

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:

Select [Function Name(Column Name),|List of Columns] from <table name>;

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:

1. Displaying Data from Multiple Tables:

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:

a) SELECT table1.column1, table2.column2.. FROM table1, table2[, table3 ];


b) SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name =
table2.column_name;
c) SELECT a.column_name, b.column_name.. FROM table1 a, table2 b WHERE a.common_field =
b.common_field;
d) Select a.column_name, b.column_name from table1 a, table1 b where a.common_field=
b.common_field;
e) SELECT column_name(s) FROM table1 [LEFT| RIGHT |FULL ] OUTER JOIN table2 ON
table1.column_name = table2.column_name;

Example:

Creation of table emp11

Syntax:

• create table emp11(id number(15), state varchar(15));

• insert into emp11 values(101, 'Delhi')

• insert into emp11 values(102, 'Goa')

• insert into emp11 values(103, 'keral')

• select * from emp11

Ouput:

Creation of table dep11

Syntax:

• create table dep11(id number(15), division varchar(15));

• insert into dep11 values(100, 'IT')

• insert into dep11 values(101, 'Sales')


• insert into dep11 values(102, 'Biotech')

• select * from dep11;

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:

6. Right Outer Join


Synatx:
select * from emp11 right join dep11 on emp11.id=dep11.id;
Output:

7. Full Outer Join


Syntax:
select * from emp11 full join dep11 on emp11.id=dep11.id;
Output:

2. Aggregating Data Using Group Functions:

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.

1. MIN() function returns the smallest value of the selected column.


2. MAX() function returns the largest value of the selected column.
3. COUNT() function returns the number of rows that matches a specified criteria.
4. AVG() function returns the average value of a numeric column.
5. SUM() function returns the total sum of a numeric column.

Syntax:

Select aggregate function(column name) from tablename;

 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.

 Having Clause: It is the substitute of WHERE for aggregate functions.

Syntax:

SELECT aggregate function(column_name), columnnames FROM table_name GROUP BY column_name(s)


ORDER BY column_name(s);

SELECT aggregate function(column_name), columnnames FROM table_name GROUP BY column_name(s)


having columnname condition(operator with value)

Example:

Table: Foodcart

Food Sold
Pizza 349
Hotdog 500
Pizza 70

1. Select min(sold) from FoodCart;


2. Select max(sold) from FoodCart;
3. Select count(sold) from FoodCart;
4. Select avg(sold) from FoodCart;
5. Select sum(sold) from FoodCart;
6. Select food, sum(sold) as totalSold from FoodCart group by food;
7. Select food, sum(sold) as totalSold from FoodCart group by food having sum(sold) > 450;
8. Select * from Foodcart order by food desc;
9. Select * from Foodcart order by sold;

3. Subqueries

Aim: Write subquery using comparison operator, IN operator, Exist operator and ANY & ALL.

Description:

 A subquery or inner query or nested query is a query within another query.

 Search Condition (Types of Subquery):


1. Subquery Comparison Test(=,<,>,<=,>=): It compares the value of an expression with a single
value produced by a subquery.

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:

Select [DISTINCT] subquery_select_parameter FROM <table_name > WHERE [test-expression](subqury);

Example :

select empno, ename, job, sal from Empl where job IN (select job from emp where sal>2000);

Questions on HELP table

1. Display topic for least sequence value

Syntax: select topic,seq from help where seq=(select min(seq) from help)

2. Display info for highest sequence value

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

Title: Manipulating data

a) Using INSERT statement

b) Using UPDATE statement

c) Using DELETE statement

2. Prior Concepts:

1. Table

3. New Concepts:

1. Insert Command
2. Update Command
3. Delete Command

4. Objectives:

1. Inserting data into the tables.


2. Update the records of the table.
3. Delete the table or some of the records of the table.

5. Procedure:

1. Identify the required column from each table.

6. Implementation:

Done by students in the lab.

6. Results:

7. O/P of the program

8. Application:

Using INSERT statement

Aim: Create table and inserting 5 Rows.

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

INSERT INTO table_name VALUES (value1, value2, value3, ...);

Example:

insert into student values(1,’Amey’,45);

select * from student;

Questions to practice:

Create following table and insert at least 5 rows in each using insert syntax.

Product(pid, pname, quantity, product_price)

Book(bid, bname, authors_name, price)

Student(roll_no, sname, dob, phone_no, class, marks)

Employee(eid, ename, phone_no, doj, job, salary, deptno )

Using UPDATE statement

Aim: Create table and updating rows.

Description: The UPDATE and SET statement is used to update records in a table.

Syntax: UPDATE table_name SET column1 = value1, column2 = value2,…WHERE condition;

Example:

Update emp set sal=15000 where empno=7788;

Questions to practice:

To solve following questions use previous table Student and Book.

Update student marks to 50 of roll no 2.

Increase product price by 100 of every product whose quantity is 2.

Update phone number from 8901236543 to 7788542454 of student ‘Rahul’.


Use Update command to increase price of book to 900 of book ‘Two States’.

Using DELETE statement

Aim: Create table and deleting rows.

Description: The DELETE statement is used to delete one or more records in a table.

Syntax: DELETE FROM table_name [.WHERE condition];

Example:

Delete from emp where empno=7788;

Questions for Practice:

To solve following question use previous tables.

Delete product ‘Parle-G’ from product table.

Delete all rows from delete table.

Delete all rows from student whose class is ‘FYBSCIT’.

Delete employee who working in deptnumber 20.


Practical: 4
1.Title:
Creating and Managing Tables
2. Prior Concepts:
1. Table
2. datatype

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

a. Creating and Managing Tables


i) Create a table person to enter personal details.
Code:
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255) );

ii) Create CUSTOMERS table and make his id as a PRIMARY KEY

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));
Output:
iii) Alter table person add a new column middle name into it .

a. Alter table persons add middle_name varchar(30);


b. Change the size of city field from 255 to 30.

Alter table person modify city varchar(30);


c. Delete the column middle name from the person table
Alter table person drop column middle_name;
iv. dropping table
delete table persons

drop table persons;

v. Renaming table
change the table name customers to customer info
rename customers to customerinfo;

vi. Truncate the table


delete all the rows from customerinfo
truncate table customerinfo;

iii. Including Constraints

Create the tables described below:

Table Name : CLIENT_MASTER

Description : Used to store client information

PRIMARY CONSTRAIN

Column Name Data Type Size Default Attributes


CLIENTNO Char 6 Primary Key/First letter must start
with ‘C’
NAME Char 20 Not Null
ADDRESS Char 20
CITY Char 15
PINCODE Number 6
STATE Char 15
BALDUE Number 10,2

CREATE TABLE CLIENT_MASTER(


CLIENT_NO CHAR(6) PRIMARY KEY,
NAME VARCHAR(20) NOT NULL,
ADDRESS VARCHAR(100),
CITY VARCHAR(15),
PINCODE NUMBER(6),
STATE VARCHAR(20),
BAL_DUE NUMBER(8,2));

2)Table Name : PRODUCT_MASTER

NOT NULL CONSTRAINT


Description : Used to store product information

Column Name Data Type Size Default Attributes


PRODUCTNO Char 6 Primary Key/First letter must start
with ‘P’
DESCRIPTION Char 15 Not Null
QTYONHAND Number 8 Not Null
REORDERLVL Number 8 Not Null
SELLPRICE Number 8,2 Not Null,Cannot be 0
COSTPRICE Number 8,2 Not Null, Cannot be 0

3)Table Name : SALESMAN_MASTER

Description : Used to store salesman information working for the company

UNIQUE CONSTRAINT

Column Name Data Type Size Default Attributes


SALESMANNO Char 6 Primary Key/First letter must
start with ‘S’
SALESMANNAME Char 20 Not Null
ADDRESS Char 30 Not Null
CONTACTNO Number Unique

CREATE TABLE SALESMAN_MASTER(


SALESMAN_NO CHAR(6) PRIMARY KEY,
SALESMAN_NAME VARCHAR(20) NOT NULL,
ADDRESS VARCHAR(100) NOT NULL,
CONTACT_NO NUMBER UNIQUE);

Table Name : SALESMAN_ORDER

Description : Used to store client’s orders

FOREIGN KEY CONSTRAINT

Column Name Data Type Size Default Attributes


ORDERNO Char 6 Primary Key
CLIENTNO Char 6
SALESMANNO Char 6 Foreign Key references SalesmanNo of
Salesman_Master table
DALYTYPE Char 1 Delivery : Part (P) / Full(F)
BILLYN Char 1
ORDERSTATUS Char 10 Values(‘In Process’,’Fulfilled’,’BackOrder’,
‘Cancelled’)
CREATE TABLE SALESMAN_ORDER(
ORDER_NO CHAR(6) PRIMARY KEY,
CLIENT_NO CHAR(6) ,
SALESMAN_NO CHAR(6),
DALYTYPE CHAR(1),
BILLYN CHAR(1),
ORDERSTATUS CHAR(10),
CONSTRAINT fk_NO
FOREIGN KEY (SALESMAN_NO)
REFERENCES SALESMAN_MASTER(SALESMAN_NO)) ;

Table Name : SALES_ORDER_DETAILS

Description : Used to store client’s orders with details of each product ordered.

Column Name Data Type Size Default Attributes


ORDERNO Varchar2 6 Foreign Key references OrderNo of Sales_Order
table
PRODUCTNO Varchar2 6 Foreign Key references ProductNo of
Product_Master
QTYORDERED Number 8
QTYDISP Number 8
PRODUCTRATE Number 10,2
Practical: 5
1.Title:
Creating and Managing other database objects
2. Prior Concepts:
1. Table
2. CREATE command

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.

create table train


(
train_no varchar2(10) primary key,
train_name varchar2(20) unique,
src varchar2(20),
destination varchar2(20)
);

ii. creating views

Create view train_view as


Select train_no,train_name from train;

Select * from train_view;


Dropping View

Dropping view train_view;

NAME VARCHAR (20) NOT NULL,


AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));

Output:

b. creating database Objects

create table passenger


( pid number(10) primary key,
name varchar2(30),
age number(20) not null );

insert into passenger values(01,'Maria',26);


insert into passenger values(02,'snehal',24);
insert into passenger values(03,'Shweta',35);
insert into passenger values(04,'Ramesh',50);
insert into passenger values(05,'Suresh',67);

SEQUENCES

i. Create a sequence on passenger table.

create sequence seqpass


minvalue 5
maxvalue 50
start with 5
increment by 1
cache 20;

ii. Insert the records into passenger through sequences including nextval() function.

insert into passenger values(seqqpass.nextval,'ram',45);


insert into passenger values(seqqpass.nextval,'sita',32);
Output:
iii. dropping sequences

drop sequence seqpass;


c. Contolling User Access

Create user

create user shweta identified by shweta123


default tablespace users
quota unlimited on users;
connect system/tiger;

Granting session to user


grant create session to shweta;

connect system/tiger;
grant create table to shweta;
connect shweta/shweta123;

user creating table


connect shweta/shweta123;

create table student


(
rollno number (3),
name varchar2(20)
);
insert into student values(01,'shweta');

connect system/tiger;

create another user


create user nita identified by nita123
default tablespace users
quota unlimited on users;
connect shweta/shweta123;

Granting select priviledge to another user


grant select on student to nita;
connect nita/nita123;
select * from usera.student;

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:

1. Finding common data between the tables


2. Calculation based on date and time
3. Selecting data from multiple table by using subqueries.

a. Using SET Operators


UNION
To select passenger id of passengers whose age is either less than 40 years or their travelling from
Mumbai?
select pid from passenger where age < 40
union
(select pid from ticket where journey_id in
(select journey_id from journey where train_no
in (select train_no from train where src='mumbai')));
UNION ALL
To find the names of passenger who are either travelling into ‘2 AC’ or travelling on 1st june 2016
select name from passenger
where pid in(select pid from ticket where journey_id in
(select journey_id from journey where date_journey='01-jun-16'))
Union all
select name from passenger
where pid in(select pid from ticket where class='2AC');

MINUS
To find the names of the passenger who are travelling to Kolkata except those who are travelling on
02/02/2014

select name from passenger where pid in(


select pid from ticket where journey_id in(
select journey_id from journey where date_journey='02-feb-2014'))
minus
select name from passenger where pid in
(select pid from ticket where journey_id in
(select journey_id from journey where train_no in
(select train_no from train where destination='kolkatta')))

INTERSECT
To find the id of the passenger who are travelling on 01/06/2016 and going to Kolkata

select pid from ticket where journey_id in(


select journey_id from journey where date_journey='01-jun-2016')
intersect
select pid from ticket where journey_id in(select journey_id from journey
where train_no in(select train_no from train where destination='kolkatta'));

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.

select journey_id ,next_day(date_journey,'wednesday') as first_sunday from journey;

iii. To find the last day of current date of journey

select last_day(date_journey) from journey;

iv. Use trunc function to truncate the date to year,month and day.

select journey_id,trunc(date_journey,'year') from journey;

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.

select round(months_between(sysdate,date_journey)) as months_after_travelling from journey;


TI ME FUNCTION
i. To display the local time.
select localtimestamp from dual;
ii. To display the current timestamp.

select current_timestamp from dual;

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.

select distinct pid from ticket


where(coach_no,class)
in(select coach_no,class from ticket where pid=1) order by pid;

ii. NON PAIRWISE SUBQUERY


Get the pid of the passenger for whom the coachno is same as passenger p03 and class is same
as passenger p02

select pid from ticket where(coach_no)


in(select coach_no from ticket where pid=3) and (class in(select class from ticket where pid=1));

iii. SELECT IN FROM 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);

iv. SCALAR SUBQUERY


To select average fare,maximum fare and total no of tickets sold using select in select clause.

select pid,(select avg(fare) from ticket) as avg_fare,(select max(fare) from ticket) as


max_fare,(select count(*) from ticket) as ticket_sold from ticket;
v. NESTED SUBQUERY
Get the name and age of the passenger travelling in sleeper class.
select name,age from passenger where pid in (select pid from ticket where class='2AC');

__________________________________________________________________________________________
________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

2. Writing Executable Statements :


In PL/SQL block SELECT, INSERT, UPDATE and DELETE statements can use to manipulate data from the
table
SELECT statement can be used to retrieve data from the table

Syntax:
DECLARE
Variables declarations
BEGIN
SELECT <select_list> INTO <variable_list> FROM <table_name> WHERE <condition>
EXCEPTION
Error handling code
END

3. Interacting with Oracle server

4. Writing Control Structures

Conditional Control, Basic Loop Statement,For loop Statement

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.

b) Writing Executable statements


declare
p int;
begin
select sal into p from emp where eid=2;
DBMS_OUTPUT.PUT_LINE(‘Salary=’||(p);

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

D)Writing Control Structure

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

ii)Using if-then-else statements

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

PL/SQL procedure successfully completed.

iii)Using Nested if-then-else statements

declare
per number;
begin
per:=&per;

if per>=75 then
DBMS_OUTPUT.PUT_LINE('Your grade: A');

elsif per>=60 then


DBMS_OUTPUT.PUT_LINE('Your grade: B');

elsif per>=50 then


DBMS_OUTPUT.PUT_LINE('Your grade: c');

elsif per>=40 then


DBMS_OUTPUT.PUT_LINE('Your grade: D');

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

PL/SQL procedure successfully completed.

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.

V)The WHILE loop:

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

Display 1 to 5 using for loop

begin
for i in 1..5
loop
dbms_output.put_line (i);
end loop;
end;
o/p:
1
2
3
4
5

Display 1 to 5 reverse using for loop

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:

PL/SQL block, basic statemenrs


3. New Concepts:

a. Working with Composite Data Types


 Composite data type is type of data items that have internal components and it can be accessed
individually. For example, collections and records.
1. Records are used to treat related but dissimilar data as a logical unit. A PL/SQL record can
have variables of different types.
a. Table based Record: The %ROWTYPE attribute enables a programmer to create
table-based and cursorbased records.
2. Collection is ordered group of elements having the same data type. Each element is
identified by unique subscript that represents its position in the collection.
a. Index-By-Table or Associative array: It is similar like array with key value pair.

b. Writing Explicit Cursors

 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.

Steps to be followed to use user-defined exceptions:


• They should be explicitly declared in the declaration section.
• They should be explicitly raised in the Execution Section.
• They should be handled by referencing the user-defined exception name in the exception section.

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

4. Implement Exception Handling

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:

a)Working with Composite Data types

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;

Record: The user defined Row datatype

create table e1(eid int,ename char(10));

select * from e1;


o/p:

eid ename
1 a
2 b
3 c

create table e2(eid int,ename char(10),esal int,did int);

select * from e2;


o/p:

EID ENAME ESAL DID


1 a 10000 10
2 b 20000 20
3 c 30000 30
4 d 40000 40

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;

select * from e1;


o/p:

eid ename
1 a
2 b
3 c
4 d

b)Writing explicit cursors


1)Using Explicit cursors

select * from emp

EID ENAME SAL DEPT

1 Neha 10000 HR
3 Nilesh 90000 HR
5 rahul 50000 HR
6 Pooja 90000 Admin
7 Nita 80000 HR

create table emp_cursor(eid int,ename char(10),sal int,dept char(10))

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

select * from emp_cursor

o/p:

EID ENAME SAL DEPT


1 Neha 10000 HR

ii)Using loops in cursors

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

1)The ZERO_DIVIDE Exception


2)The VALUE_ERROR Exception
3)The NO_DATA_FOUND Exception
4)THE OTHERS Exception

create table temp(id int,value char(20))

1)The ZERO_DIVIDE Exception

SQL>declare
x number:=1;
y number:=0;
z number;
begin
z:=x/y;
insert into temp values(z,'zero divide');
end;
/

ORA-01476: divisor is equal to zero

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

select * from temp;


o/p:

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

select * from temp;


o/p:

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

select * from temp;


o/p:

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

select * from temp;


o/p:
id value
o zero divide error
2 zero divide
0 value error
1 Too

3)The NO_DATA_FOUND Exception

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

select * from temp;


o/p:

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

1. Title: Procedures and Functions

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

Procedures and Functions are made up of:


1. A Declarative Part
2. An executable Part
3. An Optional exception handling part

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

CREATE OR REPLACE FUNCTION ADD_TWO_NOS1(A IN NUMBER,B IN NUMBER)


RETURN NUMBER IS
C NUMBER(3);
BEGIN
C:=A+B;
RETURN C;
END;
/

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:

 Triggering SQL statement


 Triggering Action
 Triggering Restriction.

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:

1. CREATE [OR REPLACE ] TRIGGER trigger_name

{BEFORE | AFTER } ddl_event

ON {[schema_name.]SCHEMA|DATABASE}

BEGIN

Action _to_ excuted

END

2. CREATE [OR REPLACE ] TRIGGER trigger_name

{BEFORE | AFTER | INSTEAD OF }

{INSERT [OR] | UPDATE [OR] | DELETE}

[OF col_name]

ON table_name

[REFERENCING OLD AS o NEW AS n]

[FOR EACH ROW]

WHEN (condition)

DECLARE

Declaration-statements
BEGIN

Executable-statements

EXCEPTION

Exception-handling-statements

END;

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:

EID ENAME SAL DEPT

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

CREATE OR REPLACE TRIGGER Aft_del


AFTER DELETE
ON EMP2
FOR EACH ROW
BEGIN
INSERT INTO EMP_trigger2 VALUES
(:OLD.EID,:OLD.ENAME,:OLD.SAL);
END;

Select * From emp_trigger2

o/p:

EID ENAME SAL


1 Neha 10000
2 Priya 20000
3 Nilesh 90000
4 Nila 40000
5 rahul 50000
6 Pooja 90000
7 Nita 80000

DELETE from emp2 where eid=2

SELECT * FROM EMP_TRIGGER2

o/p:

EID ENAME SAL

1 Neha 10000
2 Priya 20000
3 Nilesh 90000
4 Nila 40000
5 rahul 50000
6 Pooja 90000
7 Nita 80000
2 Priya 20000

You might also like