0% found this document useful (0 votes)
87 views115 pages

Pranav Phanse 23202B0063

Uploaded by

prafulphanse99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views115 pages

Pranav Phanse 23202B0063

Uploaded by

prafulphanse99
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 115

DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF3K-B
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar

Name of Student: Pranav Phanse 23202B0063

Practical No: 2
Title of Experiment Create Database schema for given application

X. Practical related questions (Provide space for answers)

Note: Below are a few sample questions for reference. Teacher must design more

suchquestions so as to ensure the achievement of identified CO.

Define Database and Database Management System

Ans:

Describe primary key.

Ans:

3. Draw E-R diagram for Library Management System.

4. Normalize the following table of EMP to 3NF

EMP(empno,ename,mgr,job,deptno,loc,dname)

XI. Exercise
How would you create a new database named EMP?

Ans: create database emp;

2. Write the SQL commands to create the EMP table with the following structure:
• empno as a number datatype with up to 4 digits
• ename as a variable character datatype up to 10 characters
• job as a variable character up to 9 characters
• mgr as a number datatype with up to 4 digits
• hiredate as a date
• sal as a number with up to 7 digits, including 2 decimal places
• comm as a number with up to 7 digits, including 2 decimal places
• deptno as a number with up to 2 digits
Ans
create table emp
(
empno number(4),
ename varchar(10),
job varchar(9),
mgr number(4),
DEPARTMENT OF INFORMATION TECHNOLOGY
hiredate date,
sal number(7,2),
comm number(7,2),
deptno number(2));

3. How would you alter the EMP table to assign the empno column as the primary
key?

Ans:

Syntax:
Alter table tablename add constraint constraintname(column name);

alter table emp add constraint empno_pk primary key(empno);


DEPARTMENT OF INFORMATION TECHNOLOGY

4. Write the SQL commands to create the DEPT table with the following structure:
• deptno as a number with up to 2 digits
• dname as a variable character datatype up to 10 characters
• loc as a variable character up to 20 characters
Ans:
create table dept
(depno number(2),
dname varchar2(10),
loc varchar2(20);
DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF3K-B
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id:23202B0063

Practical No: 3
Title of Execute DDL commands to manage Database using SQL
Experiment

XI. Practical Related Questions

Note: Below are few sample questions for reference. Teacher must design more such
questions so as to

ensure the achievement of identified CO.

(Note: Use Point VII and XIII to XV for all relevant practical exercise use blank pages

provided or attach more pages if needed.)

1. Create a table EMPLOYEE with following schema:

Emp (EMP_no as primary key, E_name, Dept_no, Dept_name, Job_id, salary)

Create table employee


(emp_no number(10) primary key,
E_name varchar2(50),
Dept_no number(10),
Dept_name varchar2(30),
Job_id number(10),
Salary number(10));
(add screenshot of the output)
DEPARTMENT OF INFORMATION TECHNOLOGY

2. Create tables EMPLOYEE and DEPARTMENT with following schema by applying Primary

and Foreign key:

Emp(empno as primary key, empname, salary, phoneno)

Dept(deptno primary key, empno foreign key, deptname, location).

Theory related Questions

1. List DDL commands with its syntax

DDL Command Significance Syntax Example


CREATE Creates new CREATE TABLE create table employees
database table_name (column1 (id NUMBER,
objects like datatype, name VARCHAR2(50));
tables, views, column2 datatype, ...);
indexes, etc.
DROP Deletes DROP TABLE table_name; drop table employees;
database
objects
permanently.
TRUNCATE Removes all TRUNCATE TABLE truncate table employees;
records from a table_name;
table but keeps
the table
structure.
RENAME Changes the Rename oldtablename to Rename employees to
name of the newtablename; emp;
table
ALTER TABLE Adds a new ALTER TABLE table_name ALTER TABLE employees
(Add Column) column to an ADD (column_name ADD (email
existing table. datatype); VARCHAR2(100));
ALTER TABLE Changes the ALTER TABLE table_name ALTER TABLE employees
(Modify data type or size MODIFY (column_name MODIFY
Column) of an existing new_datatype); (name VARCHAR2(100));
column.
ALTER TABLE Removes an ALTER TABLE table_name ALTER TABLE employees
(Drop Column) existing column DROP COLUMN DROP COLUMN email;
from a table. column_name;

2. List different SQL Binary datatypes


DEPARTMENT OF INFORMATION TECHNOLOGY
Data Type Description
VARCHAR2(size) Variable-length character string with a maximum size. size specifies
the maximum number of characters (up to 4000 bytes).
CHAR(size) Fixed-length character string. size specifies the number of
characters (up to 2000 bytes).
NUMBER(p, s) Numeric data type that can store numbers with a precision p and
scale s. p is the total number of digits, and s is the number of digits
to the right of the decimal point.
DATE Stores date and time information, including year, month, day, hour,
minute, and second.
TIMESTAMP Similar to DATE but with fractional seconds. Used for more precise
date and time data.
CLOB Character Large Object. Used to store large amounts of text data.
BLOB Binary Large Object. Used to store binary data, such as images or
multimedia files.

3. Write difference between Drop and Truncate command.

Ans:

Aspect DROP TRUNCATE


Command Type DDL DDL
Syntax DROP TABLE table_name; TRUNCATE TABLE
table_name;
Example drop table emp; truncate table emp;
Table Structure Does not retain the table structure Retains the table structure after
deletion of all rows

Purpose Remove the entire table from the Remove all rows from a table
database
Rollback Command Rollback not applicable Rollback not applicable

Memory Release Releases memory Releases memory

4. Write the use of Describe command.

Ans:
DEPARTMENT OF INFORMATION TECHNOLOGY
Describe command is used to view the structure of created table.

Syntax: desc tablename;

Example : desc emp;

XII. Exercise

Attempt following and teacher shall design and allot more questions to attain desired
outcome: (Note: Use Point VIII to X and XIII to XV for all relevant programming exercise use
blank pages provided or attach more pages if needed.)

1. Create table for stud using attributes Rollno, Studname, Percentage.

Apply primary key for rollno and

check constraint on percentage that the percentage should not be greater than 100.

Ans:

Create table stud

(rollno number(10) primary key,

Studname varchar2(30),

Percentage number(4,2) constraint percentage_ck check(percentage <= 100));


DEPARTMENT OF INFORMATION TECHNOLOGY

2. Change the stud table structure by adding column City.

Ans:

alter table stud

add city varchar2(30);

3. Increase the size by 10 of studentname column.

Ans:

alter table stud

modify studname varchar2(50);


DEPARTMENT OF INFORMATION TECHNOLOGY

4. Write the output of the following:

1. Create table

Passenger_details(passenger_name varchar2(30),

train_details varchar2(30)

,travelling_date date,

birthdate date);
Output :

2. Alter table stud add phone_no number;


DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF3K-B
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id: 23202B0063

Practical No: 4
Title of Execute DML Commands to manipulate data using SQL
Experiment

Practical related questions (Provide space for answers)

Note: Below are a few sample questions for reference. Teacher must design more such
questions to ensure the achievement of identified CO.

1.Describe check constraint.

2.Describe referential integrity constraint.

3.Explain the differences between the DELETE, DROP, and TRUNCATE commands in
SQL.

Aspect DELETE DROP TRUNCATE


Command Type DML DDL DDL
Syntax DELETE FROM DROP TABLE TRUNCATE
table_name WHERE table_name; TABLE table_name;
condition;
Example delete from emp drop table emp; truncate table emp;
where empno=10;
Table Structure Retains the table Does not retain the Retains the table
structure after table structure structure after
deletion of specific deletion of all rows
rows or all rows
Purpose Remove specific Remove the entire Remove all rows
rows from a table table from the from a table
database
Rollback Command Rollback(undo Rollback not Rollback not
operation applicable) applicable applicable

Memory Release Does not release Releases memory Releases memory


memory
DEPARTMENT OF INFORMATION TECHNOLOGY

Exercise
1.Using various syntax of insert command insert the following rows of data in the EMP
table.

1. Using various syntax of insert command insert the following rows of data in the EMP table.
ENAME DNAME JOB HIREDATE LOC
EMPNO

7876 ADAMS RESEARCH CLERK 23-MAY-87 DALLAS


7499 ALLEN SALES SALESMAN 20-FEB-81 CHICAGO
7698 BLAKE SALES MANAGER 01-MAY-81 CHICAGO
7782 CLARK ACCOUNTING MANAGER 09-JUN-81 NEW YORK
Syntax:
insert into tablename values (val1,val2,val3,....);

insert into emp values(7876,’ADAMS’,’RESEARCH’,’CLERK’,’23-MAY- 87',’DALLAS’);

2. Insert the multiple records in the EMP table using single insert command.
ENAME DNAME JOB HIREDATE LOC
EMPNO
7902 FORD RESEARCH ANALYST 03-DEC-81 DALLAS
7900 JAMES SALES CLERK 03-DEC-81 CHICAGO
DEPARTMENT OF INFORMATION TECHNOLOGY
7566 JONES RESEARCH MANAGER 02-APR-81 DALLAS
7839 KING ACCOUNTING PRESIDENT 17-NOV-81 NEW YORK

3. Delete record of SMITH from the above table


Ans:
[ Syntax: delete from tablename where columnname = value;]

delete from emp


where ename=’SMITH’;
DEPARTMENT OF INFORMATION TECHNOLOGY

4. Change the salary of Ward to 12500


Ans:
Syntax : ( Update tablename set columnname=value
Where columname=value; )

Update emp set salary =12500


Where ename=’Ward’;

5. Display contents of empno and sal

Ans:
Syntax:
Select column1name,column2name from tablename;
Select empno,salary from emp;
DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF3K-B
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar

Name of Student: Pranav Phanse 23202B0063

Practical No: 5
Title of Execute DCL commands to control the access to data using SQL
Experiment

X. Practical related questions (Provide space for answers)

1. State the use of ‘with grant options’ clause in grant command.


Ans:
• It is used to give a user the ability to grant the same privileges to other users.
• This means that when you grant a privilege to a user and include the WITH
GRANT OPTION clause, that user can pass on the granted privilege to another
user.
Syntax:
GRANT privilege ON object TO user WITH GRANT OPTION;

Example:
GRANT SELECT ON employees TO john WITH GRANT OPTION;

Now, John can not only select data from the employees table but also grant the SELECT
privilege on the employees table to other users.

2. Consider table EMPLOYEE and DEPARTMENT with following schema:


EMP (empno, empname, salary, phno)
Dept (deptno, empno, deptname, location, jobtype)
Write the output of the following queries:

• Create user Jay identifies by any admin;


• Grant create table, create view to Jay;
• Grant select, insert, update on Emp to Jay;
• Grant select, update (deptno, empno) on Dept to Jay;
• Alter user Jay identified by admin;
• Revoke create table, create views from Jay;
• Revoke select, insert, update on Emp from Jay;
• Create role emp_pvr;
DEPARTMENT OF INFORMATION TECHNOLOGY
• Grant create table, create views to emp_pvr;
• Grant emp_pvr to Jay, John;

1. Create user Jay identifies by any admin;


CREATE USER Jay IDENTIFIED BY admin;

2. Grant create table, create view to Jay;


GRANT CREATE TABLE, CREATE VIEW TO Jay;

3. Grant select, insert, update on Emp to Jay;


GRANT SELECT, INSERT, UPDATE ON Emp TO Jay;

4. Grant select, update (deptno, empno) on Dept to Jay;


GRANT SELECT, UPDATE (deptno, empno) ON Dept TO Jay;

5. Alter user Jay identified by admin;


ALTER USER Jay IDENTIFIED BY admin;

6. Revoke create table, create views from Jay;


REVOKE CREATE TABLE, CREATE VIEW FROM Jay;

7. Revoke select, insert, update on Emp from Jay;


REVOKE SELECT, INSERT, UPDATE ON Emp FROM Jay;

8. Create role emp_pvr;


CREATE ROLE emp_pvr;

9. Grant create table, create views to emp_pvr;


GRANT CREATE TABLE, CREATE VIEW TO emp_pvr;

10. Grant emp_pvr to Jay, John;


GRANT emp_pvr TO Jay, John;

XI. Exercise
Attempt following and teacher shall design and allot more questions to attain desired
outcome: (Note: Use Point VIII to X and XIII to XV for all relevant programming
exercise use blank pages provided or attach more pages if needed.)

1. Create the user Jay


CREATE USER Jay IDENTIFIED BY password;

2. Grant select, insert, delete privileges on Emp and Dept table


GRANT SELECT, INSERT, DELETE ON Emp TO Jay;
GRANT SELECT, INSERT, DELETE ON Dept TO Jay;
DEPARTMENT OF INFORMATION TECHNOLOGY
3. Grant update privilege on columns empno and salary on Emp table
GRANT UPDATE (empno, salary) ON Emp TO Jay;

4. Revoke all above privileges from Emp and Dept table


REVOKE SELECT, INSERT, DELETE ON Emp FROM Jay;
REVOKE SELECT, INSERT, DELETE ON Dept FROM Jay;
REVOKE UPDATE (empno, salary) ON Emp FROM Jay;

5. Create role dept_pvr


CREATE ROLE dept_pvr;

6. Assign system privileges - create table, create view to role dept_pvr


GRANT CREATE TABLE, CREATE VIEW TO dept_pvr;

7. Assign above system privileges to users Jay and John


GRANT dept_pvr TO Jay;
GRANT dept_pvr TO John;

8. Assign object privileges - select, insert, delete to role dept_pvr


GRANT SELECT, INSERT, DELETE ON Emp TO dept_pvr;
GRANT SELECT, INSERT, DELETE ON Dept TO dept_pvr;

9. Assign above object privileges to users Jay and John


GRANT dept_pvr TO Jay;
GRANT dept_pvr TO John;
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject: Database Management System Subject Code: 313315
Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id: 23202B0063

Practical No: 7
Title of Write Queries using Arithmetic operators.
Experiment

X. Practical related questions (Provide space for answers)

1. What is precedence/ SQL arithmetic order in arithmetic operators?


Ans:
The precedence (order) of SQL arithmetic operators determines the sequence in which the
operations are evaluated. The order follows standard mathematical conventions. Here’s
the order of precedence for arithmetic operators in SQL:
1. Parentheses (): Operations within parentheses are performed first.
2. Multiplication * and Division /: These operations are performed next, from left to
right.
3. Addition + and Subtraction -: These operations are performed last, from left to right.

Example
SELECT 2 + 3 * 4 - 5 / (1 + 1) FROM dual;

The operations are evaluated in the following order:


1. Parentheses: 1 + 1 results in 2
2. Division: 5 / 2 results in 2.5
3. Multiplication: 3 * 4 results in 12
4. Addition and Subtraction: 2 + 12 - 2.5 results in 11.5

Result
SELECT 2 + 3 * 4 - 5 / (1 + 1) AS Result FROM dual;
-- Result: 11.5

2. Explain the SQL exponentiation operator.


Ans:
If you want to calculate 2 raised to the power of 3 (2^3), you can use the POWER
function:

SELECT POWER(2, 3) AS Result FROM dual;

This query calculates 2 raised to 3 , which is 8, and returns it as Result as 8


DEPARTMENT OF INFORMATION TECHNOLOGY

3. List few compound operators.


Ans:
Compound Description Example
Operator
+= Adds a value to a variable and assigns the num += 10;
result
-= Subtracts a value from a variable and assigns num -= 5;
the result
*= Multiplies a variable by a value and assigns the num *= 4;
result
/= Divides a variable by a value and assigns the num /= 2;
result

Syntax 1: To display all rows and all columns


Select * from table name;

Example 1 :
Select * from orders;

Syntax 2: To display specific columns of the table


Select column1name , column2name,.. From table name;

Example:
Select cust_id,amount from orders;

NOTE: REFER SCHEMA FOR displaying specific columns


DEPARTMENT OF INFORMATION TECHNOLOGY
COLUMN ALIAS:

Display column name of your choice in the output of select


command

1)

From Orders(cust_id, order_id, items, amount) this schema if you


want to display the amount column as “Paid Cost” then
• Select cust_id,amount “Paid Cost” from orders;
• Select cust_id,amount as Paid Cost from orders;
XI. Exercise
1. Consider the following schema

Orders(cust_id, order_id, items, amount)

Write queries for the following:


i Display new column named total_amount which is 200 added to the amount field.

Ans:

SELECT cust_id, order_id, items, amount, amount + 200 AS total_amount FROM Orders;

ii Display new column named offer_price which is 100 subtracted from the amount field.

Ans:

SELECT cust_id, order_id, items, amount, amount - 100 AS offer_price FROM Orders;
DEPARTMENT OF INFORMATION TECHNOLOGY

iii Display new column named revised_amount which is multiplied by 5 times the amount
field.

Ans:

SELECT cust_id, order_id, items, amount, amount * 5 AS revised_amount FROM Orders;

iv Display new column named half_amount which is divided by 2 to the amount field.

Ans:

SELECT cust_id, order_id, items, amount, amount / 2 AS half_amount FROM Orders;


DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
DEPARTMENT OF INFORMATION TECHNOLOGY
Name of Student: Roll Id:

Practical No: 8
Title of Apply built-in Logical operators on given data
Experiment

X. Practical related questions (Provide space for answers)

1. Explain the need of logical operators in SQL


Ans:
Logical operators in SQL are used to combine or modify conditions in SQL queries.
They help you filter data based on multiple criteria.

2. List three logical operators and describe them with an example.


Ans:

AND: Combines two or more conditions and returns true only if all conditions are
true.

Example:
Find orders where the amount is greater than 100 and the customer ID is 1.
SELECT * FROM Orders
WHERE
amount > 100 AND cust_id = 1;

OR: Combines two or more conditions and returns true if at least one condition is
true.

Example:
Find orders where the amount is greater than 100 or the customer ID is 1.
SELECT * FROM Orders
WHERE
amount > 100 OR cust_id = 1;

NOT: Negates a condition, returning true if the condition is false.


Example:
Find orders where the customer ID is not 1.
SELECT * FROM Orders
WHERE NOT cust_id = 1;

XI. Exercise

Consider the following schema


DEPARTMENT OF INFORMATION TECHNOLOGY
Emp(empno,ename,job,mgr,hiredate,sal,comm,deptno)

Write queries for the following:


iv Display employees whose city is ‘Mumbai’ and earns more than 50000

Ans:

select * from emp

where city=’Mumbai’ and sal >50000;

iv Display employees who job is Clerk or commission is 500

Ans:

select * from emp

where job=’Clerk’ or comm=500;

iv Display details of employees whose salary is between 20000 and 50000.

Ans:

select * from emp

where sal between 20000 and 50000;


DEPARTMENT OF INFORMATION TECHNOLOGY

iv Display details of employees who stays at Mumbai, Pune, Nashik or Nagpur

Ans:

Select * from emp where

City in (‘Mumbai’,’Pune’,’Nashik’,’Nagpur’);

Exercise
DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id: 23202B0063

Practical No: 9
Title of Implement Relational operators to apply various conditions in
Experiment query.

XI. Exercise

1. Consider the following schema Student (stu_name, course_id, Roll_no, percentage)

Write queries for the following:

i. Select stu_name, course_id, from Student WHERE percentage is >=60 and <=100;

Ans:

Select stu_name,course_id from student

Where percentage>=60 and percentage <=100;

Or

Select stu_name,course_id from student

Where percentage between 60 and 100;


DEPARTMENT OF INFORMATION TECHNOLOGY

ii. Select details of students whose Roll numbers are above 15;

Ans:

Select * from student

Where Roll_no >15;

iii. Select stu_id, Roll_no from Student WHERE course_id! =121;

Ans:

Select stu_id, Roll_no from student

where student course_id != 121;


DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id: 23202B0063

Practical No: 10
Title of Experiment Use Set operators to perform different operations

X. Practical related questions (Provide space for answers)

1. Explain the need of set operators in SQL


Ans:
● Set operators in SQL, like UNION, UNION ALL INTERSECT, and MINUS, are used
to combine results from multiple queries into a single result set.
● They help you compare, merge, or filter data from different tables or queries
efficiently.
● This makes it easier to analyze data that spans across multiple sources or conditions.

2. Describe various set operators in SQL


Ans:

1. UNION

Description:

The UNION operator combines the results of two or more SELECT queries into a single result
set. It removes duplicate rows, so each row in the result is unique.

Syntax:

SELECT column_name(s) FROM table1


UNION
SELECT column_name(s) FROM table2;
DEPARTMENT OF INFORMATION TECHNOLOGY
Table: students_mumbai

first_name
Aarav
Ananya
Ishaan
Priya
Rohan

Table: students_delhi

first_name
Aarav
Ananya
Ishaan
Priya
Rohit

Example:

SELECT first_name FROM students_mumbai


UNION
SELECT first_name FROM students_delhi;

Explanation:

This query combines the first_name columns from the students_mumbai and students_delhi
tables. If a name appears in both tables, it will be shown only once in the output.

Output:

first_name
Aarav
Ananya
Ishaan
Priya
Rohit

2. UNION ALL

Description:
DEPARTMENT OF INFORMATION TECHNOLOGY
The UNION ALL operator also combines results from multiple SELECT queries into a single
result set, but it does not remove duplicate rows. All rows from each query are included in the
result.

Syntax:

SELECT column_name(s) FROM table1


UNION ALL
SELECT column_name(s) FROM table2;

Example:

SELECT first_name FROM students_mumbai


UNION ALL
SELECT first_name FROM students_delhi;

Explanation:

This query combines the first_name columns from the students_mumbai and students_delhi
tables, including all duplicates.

Output:

first_name
Aarav
Ananya
Aarav
Ishaan
Priya
Rohit

3. INTERSECT

Description:

The INTERSECT operator returns only the rows that are common between two SELECT
queries. It shows only the duplicate values that exist in both result sets.

Syntax:

SELECT column_name(s) FROM table1


INTERSECT
SELECT column_name(s) FROM table2;
DEPARTMENT OF INFORMATION TECHNOLOGY
Example:

SELECT first_name FROM students_mumbai


INTERSECT
SELECT first_name FROM students_delhi;

Explanation:

This query returns the names that appear in both the students_mumbai and students_delhi
tables.

Output:

first_name
Aarav

4. MINUS

Description:

The MINUS operator returns only the rows that are in the first SELECT query but not in the
second. It's used to find differences between two result sets.

Syntax:

SELECT column_name(s) FROM table1


MINUS
SELECT column_name(s) FROM table2;

Example:

SELECT first_name FROM students_mumbai


MINUS
SELECT first_name FROM students_delhi;

Explanation:

This query returns the names that are in the students_mumbai table but not in the students_delhi
table.

Output:

first_name
DEPARTMENT OF INFORMATION TECHNOLOGY
Ananya
Ishaan

XI. Exercise

1. Consider following Schema :

emp1(empno,ename,deptno)

emp2(empno,ename,deptno)

Create these two tables

Table: emp1

empno ename deptno


101 Aarav 10
102 Priya 20
103 Aryan 30
104 Ananya NULL
105 Rohan 20

Table: emp2

empno ename deptno


201 Rohan 20
202 Ananya 30
203 Isha NULL
204 Vikram 40
205 Priya NULL

Write SQL commands for the following statements.

1. Display the names of employees including duplicate employee names.

SELECT ename FROM emp1

UNION ALL

SELECT ename FROM emp2;


DEPARTMENT OF INFORMATION TECHNOLOGY

2. Display the names of employees excluding duplicate employee names.

SELECT ename FROM emp1

UNION

SELECT ename FROM emp2;

3. Display the common employee names from both the tables.

SELECT ename FROM emp1

INTERSECT

SELECT ename FROM emp2;


DEPARTMENT OF INFORMATION TECHNOLOGY

4. List employees who are not assigned to any department?

SELECT ename FROM emp1

MINUS

SELECT ename FROM emp2;

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF3K-B
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id: 23202B0063

Practical No: 11
Title of Experiment Execute queries using string functions

X. Practical related questions (Provide space for answers)

1. What is REPLACE string functions?


DEPARTMENT OF INFORMATION TECHNOLOGY
Ans:
Description:
The REPLACE function in SQL is used to replace occurrences of a substring within a string
with another substring.

Example
SELECT REPLACE('Hello World', 'World', 'Everyone') FROM DUAL;

Output:

2. What is the function of SPACE string function?


Ans:

Description:
The SPACE function generates a string of spaces with a specified length.

Example:
SELECT SPACE(5) FROM DUAL;

Output:

SPACE(5)
(5 spaces)

3. What output you get when you compare two strings using STRCMP built in string
function?
Ans:

Description:

The STRCMP function compares two strings and returns an integer value:

● 0 if the strings are equal,


● A negative number if the first string is less than the second,
● A positive number if the first string is greater than the second.

Example:

SELECT STRCMP('apple', 'banana') FROM DUAL;

Output:
STRCMP('apple', 'banana')
-1
DEPARTMENT OF INFORMATION TECHNOLOGY
XI. Exercise
1. Write output of the following queries.
● Select concat (‘Jay’ ‘IITB’) from Dual;

Output:

● Select ltrim (‘Shreya’,’s’) from Dual;

Output:

● Select upper(‘raj’) from Dual;

Output:
DEPARTMENT OF INFORMATION TECHNOLOGY

● Select rpad (“HR’, 10, ‘*’) from Dual;

Output:
DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF3K-B
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id: 23202B0063

Practical No: 12
Title of Experiment Execute queries using Arithmetic functions

X. Practical related questions (Provide space for answers)

1.Differentiate between round() and trunc()

1. ROUND() vs. TRUNC()

Points of
ROUND() TRUNC()
Differentiation
Rounds a number to the Truncates a number, removing decimals
Purpose
nearest value. without rounding.
ROUND(number,[decimal_
Syntax TRUNC(number, [decimal_places])
places])
SELECT ROUND(12.3456, SELECT TRUNC(12.3456, 2) FROM
Example Query
2) FROM DUAL; DUAL;
Output 12.35 12.34

2.Differentiate between floor() and ceil()

2. FLOOR() vs. CEIL()

Points of
FLOOR() CEIL()
Differentiatio
DEPARTMENT OF INFORMATION TECHNOLOGY
n
Returns the largest integer less Returns the smallest integer greater
Purpose
than or equal to the number. than or equal to the number.
Syntax FLOOR(number) CEIL(number)
Example SELECT FLOOR(12.75) FROM SELECT CEIL(12.75) FROM
Query DUAL; DUAL;
Output 12 13

3.List arithmetic functions which are not listed here.

Ans 1. Addition(+)
2. Subtraction(-)
3. Division(/)
4. Multiplication(*)

XI. Exercise

1.Calculate cube of following numbers: 12,14,16

SELECT POWER(12, 3) AS cube_of_12,


POWER(14, 3) AS cube_of_14,
POWER(16, 3) AS cube_of_16
FROM DUAL;
UBE_OF_12 CUBE_OF_14 CUBE_OF_16
1728 2744 4096

2.Display details of salary of employees with roundup value.

SELECT empno, ename, salary, CEIL(salary) AS rounded_salary FROM employees;


DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse- Roll Id: 23202B0063

Practical No: 13
Title of Experiment Implement queries using Date and Time functions

X. Practical related questions (Provide space for answers)


1. Write the use of format () function with syntax and example.
Ans:
The FORMAT() function in SQL is used to format a number as a string with a specified format.

Syntax:
Select FORMAT(number, decimal_places) from dual;

Example:
SELECT FORMAT(1234.567, 2) FROM dual;

2. Write the use of months_between function with syntax and example.


Ans:
DEPARTMENT OF INFORMATION TECHNOLOGY
The MONTHS_BETWEEN() function in SQL calculates the number of months between two dates.
Syntax:
Select MONTHS_BETWEEN(date1, date2) from dual;

Example:
SELECT MONTHS_BETWEEN('2024-09-01', '2024-06-01') FROM dual;

3. Write the syntax for displaying the local time stamp.


Ans:
To display the local timestamp in SQL, you can use the CURRENT_TIMESTAMP function.

SELECT CURRENT_TIMESTAMP FROM dual;

This returns the current date and time, including the time zone.

XI. Exercise
1. Write output of the following queries.
a. Select sysdate from Dual;

b. Select last_day() from Dual;

c. Select dayofweek() from Dual;


DEPARTMENT OF INFORMATION TECHNOLOGY

d. Select last_day(sysdate) from Dual;


DEPARTMENT OF INFORMATION TECHNOLOGY
Subject: Database Management System Subject Code: 313315
Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id: 23202B0063

Practical No: 14
Title of Experiment Implement queries using Aggregate functions

X. Practical related questions (Provide space for answers)

1. Describe group functions or aggregate functions in SQL


Ans:

Group functions, also called aggregate functions, in SQL perform calculations on a set of rows and
return a single result. These functions are useful for summarizing data.

Serial
Group Function Explanation of Group
Numbe Example
Name Function
r
AVG() Returns average value of SELECT AVG(salary)
1
specified column FROM emp;
SUM() Returns summation of SELECT SUM(salary)
2
specified column FROM emp;
MIN() Returns lowest value of SELECT MIN(salary)
3
specified column FROM emp;
MAX() Returns highest value of SELECT MAX(salary)
4
specified column FROM emp;
COUNT (*) Counts all rows including SELECT COUNT(*) FROM
5
duplicates and nulls emp;
COUNT Counts number of values SELECT COUNT(comm)
6 (column_name) in specified column FROM emp;
excluding nulls
COUNT Counts distinct non-null SELECT
7 (DISTINCT values in specified column COUNT(DISTINCT deptno)
column_name) FROM emp;
DEPARTMENT OF INFORMATION TECHNOLOGY
2. Differentiate between count(*) and count(columname)
COUNT(columnname)
Criteria
COUNT(*)
Counts all rows, including Counts only non-NULL values in the
NULLs. column.
Counts all rows
Excludes rows with NULL values.
NULL values Includes rows with
NULL values.
Slightly faster, as it Slightly slower due to checking column
Performance doesn't check column values.
values.
Used when you want to count non-NULL
Use Used when you need values in a specific column.
to count total rows.

XI. Exercise
Consider the following schema
Emp(empno,ename,job,mgr,hiredate,sal,comm,deptno)

CREATE TABLE Emp


( empno NUMBER(4) PRIMARY KEY,
ename VARCHAR2(10),
job VARCHAR2(9),
mgr NUMBER(4),
hiredate DATE,
sal NUMBER(7, 2),
comm NUMBER(7, 2),
deptno NUMBER(2) );

INSERT INTO Emp VALUES (7369, 'SMITH', 'CLERK', 7902, '17-DEC-1980', 800, NULL,
20);

INSERT INTO Emp VALUES (7499, 'ALLEN', 'SALESMAN', 7698, '20-FEB-1981', 1600,
300, 30);

INSERT INTO Emp VALUES (7521, 'WARD', 'SALESMAN', 7698, '22-FEB-1981', 1250,
500, 30);

INSERT INTO Emp VALUES (7566, 'JONES', 'MANAGER', 7839, '02-APR-1981', 2975,
NULL, 20);

INSERT INTO Emp VALUES (7654, 'MARTIN', 'SALESMAN', 7698, '28-SEP-1981', 1250,
1400, 30);

INSERT INTO Emp VALUES (7698, 'BLAKE', 'MANAGER', 7839, '01-MAY-1981', 2850,
NULL, 30);

INSERT INTO Emp VALUES (7782, 'CLARK', 'MANAGER', 7839, '09-JUN-1981', 2450,
NULL, 10);
DEPARTMENT OF INFORMATION TECHNOLOGY
INSERT INTO Emp VALUES (7788, 'SCOTT', 'ANALYST', 7566, '19-APR-1987', 3000,
NULL, 20);

INSERT INTO Emp VALUES (7839, 'KING', 'PRESIDENT', NULL, '17-NOV-1981', 5000,
NULL, 10);

INSERT INTO Emp VALUES (7844, 'TURNER', 'SALESMAN', 7698, '08-SEP-1981', 1500,
0, 30);

INSERT INTO Emp VALUES (7900, 'JAMES', 'CLERK', 7698, '03-DEC-1981', 950, NULL,
30);

INSERT INTO Emp VALUES (7902, 'FORD', 'ANALYST', 7566, '03-DEC-1981', 3000,
NULL, 20);

INSERT INTO Emp VALUES (7934, 'MILLER', 'CLERK', 7782, '23-JAN-1982', 1300,
NULL, 10);

1. Display the minimum, maximum, sum and average salary of all employees. Label
the columns Maximum, Minimum, Sum and Average respectively.

Ans:
SELECT MIN(sal) AS Minimum, MAX(sal) AS Maximum, SUM(sal) AS
Sum, AVG(sal) AS Average FROM Emp;
DEPARTMENT OF INFORMATION TECHNOLOGY
2. Determine the number of managers without listing them. Label the column
number of managers
Ans:
SELECT COUNT(*) AS "Number of Managers"
FROM Emp
WHERE job = 'MANAGER';

3. Write a query that will display the difference between the highest and lowest
salaries. Label the column DIFFERENCE.
Ans:

SELECT MAX(sal) - MIN(sal) AS DIFFERENCE FROM Emp;

4. Display the number of employees in department 10 who earns a commission


Ans:

SELECT COUNT(*) FROM Emp

WHERE deptno = 10 AND comm IS NOT NULL;


DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id: 23202B0063

Practical No: 15
Title of Experiment Execute queries for Ordering and Grouping data.

X. Practical related questions (Provide space for answers)

Create Two Tables Emp and Dept, Consider the following schema
Emp (Emp_no as primary key, E_name, Dept_no, Dept_name, name, Job_id, Salary)
and
Dept (Dept_no as primary key, emp_no foreign key, Dept_name, location)

-- Step 1: Create Tables Without Foreign Keys

-- Create Dept table without foreign keys


CREATE TABLE Dept (
DEPARTMENT OF INFORMATION TECHNOLOGY
Dept_no NUMBER PRIMARY KEY,
emp_no NUMBER, -- To be referenced later
deptname VARCHAR2(50),
location VARCHAR2(50)
);

-- Create Emp table without foreign keys


CREATE TABLE Emp (
Emp_no NUMBER PRIMARY KEY,
E_name VARCHAR2(50),
Dept_no NUMBER, -- To be referenced later
Dept_name VARCHAR2(50),
name VARCHAR2(50),
Job_id VARCHAR2(10),
Salary NUMBER(10, 2)
);

-- Step 2: Insert Data into Tables

-- Insert into Emp table


INSERT INTO Emp VALUES (1001, 'John Smith', 10, 'HR', 'John', 'MGR', 60000);
INSERT INTO Emp VALUES (1002, 'Alice Johnson', 20, 'Sales', 'Alice', 'SALES',
55000);
INSERT INTO Emp VALUES (1003, 'Michael Brown', 30, 'IT', 'Michael', 'DEV',
70000);
INSERT INTO Emp VALUES (1004, 'Jessica Williams', 40, 'Finance', 'Jessica',
'ACCT', 62000);
INSERT INTO Emp VALUES (1005, 'David Miller', 50, 'Marketing', 'David', 'MKTG',
48000);
INSERT INTO Emp VALUES (1006, 'Sophia Davis', 60, 'Operations', 'Sophia', 'OPS',
53000);
INSERT INTO Emp VALUES (1007, 'James Wilson', 70, 'R&D', 'James', 'RND',
75000);

-- Insert into Dept table


INSERT INTO Dept VALUES (10, 1001, 'HR', 'New York');
INSERT INTO Dept VALUES (20, 1002, 'Sales', 'Chicago');
INSERT INTO Dept VALUES (30, 1003, 'IT', 'San Francisco');
INSERT INTO Dept VALUES (40, 1004, 'Finance', 'Dallas');
INSERT INTO Dept VALUES (50, 1005, 'Marketing', 'Boston');
INSERT INTO Dept VALUES (60, 1006, 'Operations', 'Seattle');
INSERT INTO Dept VALUES (70, 1007, 'R&D', 'Los Angeles');

-- Step 3: Add Foreign Key Constraints

-- Add foreign key constraint to Emp for Dept_no


ALTER TABLE Emp
DEPARTMENT OF INFORMATION TECHNOLOGY
ADD CONSTRAINT fk_dept
FOREIGN KEY (Dept_no)
REFERENCES Dept(Dept_no);

-- Add foreign key constraint to Dept for emp_no


ALTER TABLE Dept
ADD CONSTRAINT fk_emp
FOREIGN KEY (emp_no)
REFERENCES Emp(Emp_no);

1. Display the information of the tables using SELECT command.


Ans:
DEPARTMENT OF INFORMATION TECHNOLOGY

2. Execute the SQL queries using SELECT, WHERE, GROUP BY clause.


Ans:
Write a query to display the total salary paid to employees in each department, grouped by department
name.
SELECT Dept_name, SUM(Salary) AS Total_Salary
FROM Emp
GROUP BY Dept_name;

SELECT E_name, Dept_name, Salary


FROM Emp
WHERE Salary > 60000
ORDER BY Salary DESC;

3. Execute the SQL queries using SELECT, WHERE, GROUP BY and HAVING
clause.
DEPARTMENT OF INFORMATION TECHNOLOGY
Ans:
1)Write a query to find the total salary for each department and display only those
departments where the total salary is greater than 150,000.

SELECT Dept_name, SUM(Salary) AS Total_Salary


FROM Emp
GROUP BY Dept_name
HAVING SUM(Salary) > 150000;
(Paste Output and write in one line about output i.e. Query question)

2)Write a query to display the employee names, department names, and salaries of
employees who earn more than 60,000. The results should be ordered by salary in
descending order.
SELECT e_name, Dept_name, COUNT(E_name) AS Employee_Count
FROM Emp
WHERE Salary > 60000
GROUP BY Dept_name, e_name;

(Paste Output and write in one line about output i.e. Query question)

1. Execute the SQL queries using SELECT, WHERE, ORDER BY clause.


Ans:
SELECT E_name, Salary
FROM Emp
WHERE Salary > 55000
ORDER BY Salary DESC;
DEPARTMENT OF INFORMATION TECHNOLOGY

2. Write the advantages of using the Order By clause.


Ans:

● Organizes Data: Arranges data in order (like alphabetically or by numbers).


● Quick Access: Helps find important details faster.
● Custom Sorting: Lets you choose ascending or descending order.
● Improves Presentation: Makes data easier to understand and more professional-looking.

XI. Exercise

Write output of the following queries.


1. Display minimum salary of employee from every department;
SELECT Dept_name, MIN(Salary) AS Min_Salary
FROM Emp
GROUP BY Dept_name;

2. Display total salary of every department.


SELECT Dept_name, SUM(Salary) AS Total_Salary
FROM Emp
GROUP BY Dept_name;
DEPARTMENT OF INFORMATION TECHNOLOGY

3. Display the department having total employees more than 5.


SELECT Dept_name, COUNT(Emp_no)
FROM Emp
GROUP BY Dept_name
HAVING COUNT(Emp_no) > 5;

4. Display details of employees with employee name in ascending order.


SELECT *
FROM Emp
ORDER BY E_name;

5. Display emp_no, dept_no from dept Group By deptname.


SELECT emp_no, Dept_no
FROM Dept
DEPARTMENT OF INFORMATION TECHNOLOGY
GROUP BY deptname, emp_no, Dept_no;
DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id:23202B0063

Practical No: 16
Title of Experiment Implement SQL queries for Inner and Outer Join

X. Practical related questions (Provide space for answers)


1. Define Join. List types of Joins.
Ans:
A Join in SQL is used to combine rows from two or more tables based on a related column.

Types of Joins:

● Inner Join
● Left Join (or Left Outer Join)
● Right Join (or Right Outer Join)
● Full Join (or Full Outer Join)
● Cross Join

2. Describe outer join.


Ans:

Outer Join: An Outer Join returns all rows from one table and the matching rows from another table. If
there is no match, NULL is shown. It has three types:

Below are the EMP and DEPT tables

EMP Table:

EMPNO ENAME JOB MGR HIREDATE SAL DEPTNO


101 Nikhil Clerk NULL 10-JAN-20 3000 20
102 Sumit Manager NULL 01-JUN-15 6000 20
103 Amit Clerk 102 15-MAR-21 2500 20
104 Suresh Analyst 102 20-AUG-18 5000 30
105 Ravi Clerk 104 12-DEC-19 2200 30
106 Priya Analyst 102 05-SEP-17 4500 20
107 Ramesh Clerk NULL 01-MAR-20 2800 NULL
DEPARTMENT OF INFORMATION TECHNOLOGY

DEPT Table:
DEPTNO DNAME LOC
10 Accounting New York
20 Sales Chicago
30 Research Dallas
40 Operations Boston

These tables represent employees and departments, with a relationship between the DEPTNO
in both tables.

● Left Outer Join: Returns all rows from the left table.

This will return all records from the left table (EMP), and matched records from the
right table (DEPT). If there is no match, NULL values will be shown for the right table's
columns.

SELECT e.empno, e.ename, e.deptno, d.dname


FROM emp e
LEFT OUTER JOIN dept d ON e.deptno = d.deptno;

Sample Output:
EMPNO ENAME DEPTNO DNAME
101 Nikhil 20 Sales
102 Sumit 20 Sales
103 Amit 20 Sales
104 Suresh 30 Research
105 Ravi 30 Research
106 Priya 20 Sales
107 Ramesh NULL NULL

In this case, Ramesh has no department, so the deptno and dname are NULL.

● Right Outer Join: Returns all rows from the right table.

This will return all records from the right table (DEPT), and matched records from the
left table (EMP). If there is no match, NULL values will be shown for the left table's
columns.

SELECT e.empno, e.ename, e.deptno, d.dname


FROM emp e
RIGHT OUTER JOIN dept d ON e.deptno = d.deptno;
DEPARTMENT OF INFORMATION TECHNOLOGY

Sample Output:

EMPNO ENAME DEPTNO DNAME


101 Nikhil 20 Sales
102 Sumit 20 Sales
103 Amit 20 Sales
106 Priya 20 Sales
104 Suresh 30 Research
105 Ravi 30 Research
NULL NULL 40 Operations

Here, the department Operations (deptno 40) has no employees, so empno and ename are NULL.

● Full Outer Join: Returns all rows from both tables.

This will return all records when there is a match in either the left (EMP) or right
(DEPT) table. Rows without a match will show NULL values for the missing columns.

SELECT e.empno, e.ename, e.deptno, d.dname


FROM emp e
FULL OUTER JOIN dept d ON e.deptno = d.deptno;

Sample Output:

EMPNO ENAME DEPTNO DNAME


101 Nikhil 20 Sales
102 Sumit 20 Sales
103 Amit 20 Sales
104 Suresh 30 Research
105 Ravi 30 Research
106 Priya 20 Sales
107 Ramesh NULL NULL
NULL NULL 40 Operations

In this case, both Ramesh (from EMP) without a department and the Operations department
(from DEPT) without employees are included with NULLs.
DEPARTMENT OF INFORMATION TECHNOLOGY

XI. Exercise
1. Display employee Nikhil’s employee number, name, department number, and
department location.
2. Display the list of employees who work in the sales department.
3. Display the list of employees who do not work in the sales department.
4. Display the employee names and salary of all employees who report to Sumit Patil.

Create Table Command:

CREATE TABLE emp (


empno NUMBER(4) PRIMARY KEY,
ename VARCHAR2(50),
job VARCHAR2(50),
mgr NUMBER(4),
hiredate DATE,
sal NUMBER(7, 2),
deptno NUMBER(2)
);

CREATE TABLE dept (


deptno NUMBER(2) PRIMARY KEY,
dname VARCHAR2(50),
loc VARCHAR2(50)
);

Inserting rows into a table:


INSERT INTO dept VALUES (10, 'Accounting', 'New York');
INSERT INTO dept VALUES (20, 'Sales', 'Chicago');
INSERT INTO dept VALUES (30, 'Research', 'Dallas');
INSERT INTO dept VALUES (40, 'Operations', 'Boston');

INSERT INTO emp VALUES (101, 'Nikhil', 'Clerk', NULL, '10-JAN-2020', 3000, 20);
INSERT INTO emp VALUES (102, 'Sumit Patil', 'Manager', NULL, '01-JUN-2015', 6000, 20);
INSERT INTO emp VALUES (103, 'Amit', 'Clerk', 102, '15-MAR-2021', 2500, 20);
INSERT INTO emp VALUES (104, 'Suresh', 'Analyst', 102, '20-AUG-2018', 5000, 30);
INSERT INTO emp VALUES (105, 'Ravi', 'Clerk', 104, '12-DEC-2019', 2200, 30);
INSERT INTO emp VALUES (106, 'Priya', 'Analyst', 102, '05-SEP-2017', 4500, 20);

1. Display Nikhil’s employee number, name, department number, and department


location:

Ans:

SELECT e.empno, e.ename, e.deptno, d.loc


FROM emp e JOIN dept d
ON e.deptno = d.deptno
DEPARTMENT OF INFORMATION TECHNOLOGY
WHERE e.ename = 'Nikhil';

2. Display the list of employees who work in the sales department:

Ans:

SELECT e.ename
FROM emp e
JOIN dept d ON e.deptno = d.deptno
WHERE d.dname = 'Sales';

3. Display the list of employees who do not work in the sales department:

Ans:

SELECT e.ename
FROM emp e JOIN dept d
ON e.deptno = d.deptno
WHERE d.dname != 'Sales';

4. Display the employee names and salary of all employees who report to Sumit Patil:

Ans:

SELECT e.ename, e.sal


FROM emp e
JOIN emp m ON e.mgr = m.empno
WHERE m.ename = 'Sumit Patil';
DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id:23202B0063

Practical No: 17
Title of Experiment Create and manage Views for faster access on relations.

X. Practical related questions


a. What are synonyms, write its syntax and advantages.
Ans:
A synonym is a shortcut name for a database object like a table, view, or sequence.
It allows you to use a different, often simpler, name to refer to that object.

Syntax:

● CREATE [OR REPLACE] SYNONYM synonym_name FOR object_name;

Example:

Create synonym emp for employee;

Advantages:
● Simplifies referencing objects (like tables or views).
● Allows location transparency (can refer to remote objects).
● Provides a security layer by hiding the actual object name.

b. What is the difference between simple and composite index?


Ans:
Simple Index Composite Index
Criteria
Number of Columns Based on two or more
Based on a single column. columns

Performance Impact Optimizes queries that


Optimizes queries that filter filter by multiple columns
by one column. together.

Storage Requirement Requires more storage


Requires less storage space. space due to multiple
columns.

Usage Best for queries involving


Best for queries focusing on multiple columns in
a single column. conditions (WHERE
DEPARTMENT OF INFORMATION TECHNOLOGY
clause).

CREATE INDEX index_name CREATE INDEX


Syntax ON table_name index_name ON
(column_name); table_name
(column1, column2);

Example CREATE INDEX


CREATE INDEX idx_emp_dept ON
idx_emp_name ON employees (dept_id,
employees (name); salary);

c. What are the disadvantages of views?


Ans:
● Performance Issues: Views can slow down queries if they are complex, as the data
needs to be recomputed every time.
● Cannot Always Update: Some views, especially complex ones, cannot be updated
directly.
● Hidden Complexity: Views can hide the complexity of the underlying tables, making
troubleshooting harder.
● Dependency Issues: If the underlying tables change, the view may break or need to be
recreated.

d. Write the syntax to delete view.


Ans:
Delete from view_name where condition;

XI. Exercise
1. Write output of the following queries.
For executing these queries create emp table and insert 10 rows
CREATE TABLE emp (
emp_no NUMBER(5),
e_name VARCHAR2(50),
salary NUMBER(10, 2)
);

INSERT INTO emp VALUES (101, 'Jay', 45000);


INSERT INTO emp VALUES (102, 'Suresh', 55000);
INSERT INTO emp VALUES (103, 'Ravi', 60000);
INSERT INTO emp VALUES (104, 'Neha', 50000);
INSERT INTO emp VALUES (105, 'Anjali', 48000);
INSERT INTO emp VALUES (106, 'Rajesh', 53000);
INSERT INTO emp VALUES (107, 'Pooja', 47000);
INSERT INTO emp VALUES (108, 'Sunita', 51000);
INSERT INTO emp VALUES (109, 'Kiran', 60000);
INSERT INTO emp VALUES (110, 'Vijay', 65000);
DEPARTMENT OF INFORMATION TECHNOLOGY

a. Create view emp_view as select emp_no, ename, salary from emp;

b. Update emp_view set e_name=’Jay’ where emp_no=101;

c. Delete from emp_view where emp_no= 105;


DEPARTMENT OF INFORMATION TECHNOLOGY

d. Drop view emp_view;

e. Modify location of dept_no of dept_view;


Ans:
DROP VIEW dept_view;

CREATE or replace VIEW dept_view AS


SELECT dept_no, location
FROM dept;

2. Write output of following queries.


a. Create simple index dept_simple-index on dept table.
Ans:
CREATE INDEX dept_simple_index ON dept (dept_no);

b. Create composite index dept_composite_index on dept table.


Ans:
CREATE INDEX dept_composite_index ON dept (dept_no, location);

c. Drop index dept_simple_index and dept_composite_index.


Ans:
DROP INDEX dept_simple_index;
DROP INDEX dept_composite_index;
DEPARTMENT OF INFORMATION TECHNOLOGY

d. Create index raj on emp (empno, ename).


Ans:
CREATE INDEX raj ON emp (emp_no, e_name);

3. Write output of following queries.


a. Create sequence emp_sequence
Incremented by 2
Start with 1
Nomaxvalue
Nocycle
Cache 10;

Ans:
CREATE SEQUENCE emp_sequence
INCREMENT BY 2
START WITH 1
NOMAXVALUE
NOCYCLE
CACHE 10;

CACHE in a sequence specifies how many sequence numbers are pre-allocated and stored in
memory for faster access.

b. Alter sequence emp_sequence


Incremented by 15
Max value 1000
Cycle
Cache20;

Ans:
ALTER SEQUENCE emp_sequence
INCREMENT BY 15
MAXVALUE 1000
CYCLE
CACHE 20;

c. Drop sequence emp_sequence;


Ans:
Drop sequence emp_sequence;
DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id: 23202B0063

Practical No: 18
Title of Experiment Implement PL/SQL program using Conditional Statements

X. Practical related questions


1. List conditional statement in PL/SQL.
Ans:
● If
● If-then-else
● If-Elsif
● Nested if
● case

2. Describe any three conditional statements in PL/SQL


Ans:
Sr. Title Explanation Syntax Example Program
No.

1 If Checks a IF condition THEN DECLARE


condition and statement; END IF;
executes a x NUMBER := 10;
block of code BEGIN IF x > 5 THEN
if it's true. DBMS_OUTPUT.PUT_LINE ('x is
greater than 5');
END IF;
END;

2 If-Then- Executes one IF condition THEN DECLARE


Else block of code statement; ELSE
x NUMBER := 3;
if a condition statement2; END
is true and IF; BEGIN
another if it's
false. IF x > 5 THEN
DBMS_OUTPUT.PUT_LINE('x is
greater than 5');
ELSE
DBMS_OUTPUT.PUT_LINE('x is not
greater than 5'); END IF;
END;
DEPARTMENT OF INFORMATION TECHNOLOGY
3 If-Elsif Allows IF condition1 DECLARE
checking THEN statement1;
x NUMBER:= 3;
multiple ELSIF condition2
conditions in THEN statement2; BEGIN
sequence and ELSE statement3;
executing END IF; IF x > 5 THEN
corresponding DBMS_OUTPUT.PUT_LINE('x is
blocks of greater than 5');
code. ELSIF x = 5 THEN
DBMS_OUTPUT.PUT_LINE('x is
equal to 5');
ELSE
DBMS_OUTPUT.PUT_LINE('x is
less than 5');
END IF;
END;

4 Nested If Uses one or IF condition1 DECLARE


more if THEN IF
x NUMBER := 3;
statements condition2 THEN
inside another statement; y NUMBER := 10;
if statement.
END IF; END IF; BEGIN IF x > 5 THEN
IF y > 5 THEN
DBMS_OUTPUT.PUT_LINE('Both x
and y are greater than 5');
END IF;
END IF;
END;

XI. Exercise
1. Write a PL/SQL program that checks if a given number is positive, and if it is, prints
"Number is positive".
Ans:
DECLARE
num NUMBER := 10; -- You can change this number to test other values
BEGIN
IF num > 0 THEN
DBMS_OUTPUT.PUT_LINE('Number is positive');
ELSE
DBMS_OUTPUT.PUT_LINE('Number is not positive');
END IF;
END;
DEPARTMENT OF INFORMATION TECHNOLOGY

2. Write a PL/SQL program that asks the user for their age and then prints “You can
vote" if they are over 18, and "You cannot vote" otherwise.
Ans:
DECLARE
age NUMBER := 20; -- Replace this value or use input method in advanced scenarios
BEGIN
IF age >= 18 THEN
DBMS_OUTPUT.PUT_LINE('You can vote');
ELSE
DBMS_OUTPUT.PUT_LINE('You cannot vote');
END IF;
END;

3. Write a PL/SQL program that asks the user for percentage and then assigns grades
based on the following conditions:

Distinction (>=75%)

First Class (>=60 and <75)

Second Class (>=45 and <60)


DEPARTMENT OF INFORMATION TECHNOLOGY
Pass Class (>=40 and <45)

Fail (<40)

Ans:
DECLARE

percentage NUMBER; -- Variable to store the percentage

grade VARCHAR2(20); -- Variable to store the grade

BEGIN

-- Prompt user for percentage

DBMS_OUTPUT.PUT('Enter your percentage: ');

-- Read the input percentage

percentage := &user_input; -- Replace &user_input with the actual input method if needed

While executing in Oracle APEX write above statement like below


percentage NUMBER := :percentage; -- Use substitution variable for user input

-- Determine the grade based on the percentage

IF percentage >= 75 THEN

grade := 'Distinction';

ELSIF percentage >= 60 AND percentage < 75 THEN

grade := 'First Class';

ELSIF percentage >= 45 AND percentage < 60 THEN

grade := 'Second Class';

ELSIF percentage >= 40 AND percentage < 45 THEN

grade := 'Pass Class';

ELSE
DEPARTMENT OF INFORMATION TECHNOLOGY
grade := 'Fail';

END IF;

-- Display the grade

DBMS_OUTPUT.PUT_LINE('Your grade is: ' || grade);

END;

OR

DECLARE
percentage NUMBER := &percentage; -- Use substitution variable & for user input

While executing in Oracle APEX write above statement like below


percentage NUMBER := :percentage; -- Use substitution variable for user input

BEGIN
-- Determine and output the grade based on the percentage using CASE
CASE
WHEN percentage >= 75 THEN
DBMS_OUTPUT.PUT_LINE('Grade: Distinction');
WHEN percentage >= 60 THEN
DBMS_OUTPUT.PUT_LINE('Grade: First Class');
WHEN percentage >= 45 THEN
DBMS_OUTPUT.PUT_LINE('Grade: Second Class');
WHEN percentage >= 40 THEN
DBMS_OUTPUT.PUT_LINE('Grade: Pass Class');
ELSE
DBMS_OUTPUT.PUT_LINE('Grade: Fail');
END CASE;
END;
DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id: 23202B0063

Practical No: 19
Title of Experiment Implement PL/SQL program using Iterative Statements

X. Practical related questions


3. List Iterative statement in PL/SQL
Ans:
● loop
● For loop
● While loop

4. Write PL/SQL program using any one Iterative statement.


Ans: BEGIN
DEPARTMENT OF INFORMATION TECHNOLOGY
-- Loop to print numbers from 10 to 1

FOR i IN REVERSE 1..10 LOOP

DBMS_OUTPUT.PUT_LINE(i); -- Print the current number

END LOOP;

END;

XI. Exercise
4. Write a PL/SQL program to display multiplication table of 5 using FOR loop.
Ans:
BEGIN

FOR i IN 1..10 LOOP

DBMS_OUTPUT.PUT_LINE('5 x ' || i || ' = ' || (5 * i));

END LOOP;

END;
DEPARTMENT OF INFORMATION TECHNOLOGY

5. Write a PL/SQL program to calculate factorial of 10 by using PL/SQL WHILE LOOP


statement.
Ans:
DECLARE

num NUMBER := 10;

factorial NUMBER := 1;

i NUMBER := 1;

BEGIN

WHILE i <= num LOOP

factorial := factorial * i;

i := i + 1;

END LOOP;

DBMS_OUTPUT.PUT_LINE('Factorial of ' || num || ' is ' || factorial);

END;

6. Write a PL/SQL program to calculate the prime numbers between 1 to 50.


Ans:
DECLARE

i NUMBER; -- Variable to iterate through numbers

j NUMBER; -- Variable to check for factors


DEPARTMENT OF INFORMATION TECHNOLOGY
is_prime BOOLEAN; -- Flag to determine if a number is prime

BEGIN

-- Loop through numbers from 2 to 50

FOR i IN 2..50 LOOP

is_prime := TRUE; -- Assume the current number is prime

-- Check if the number is 2 (the only even prime)

IF i = 2 THEN

DBMS_OUTPUT.PUT_LINE(i || ' is a prime number'); -- Print 2 as prime

ELSE

-- Loop through numbers from 2 to half of i to check for factors

FOR j IN 2..i/2 LOOP

-- Check if i is divisible by j

IF MOD(i, j) = 0 THEN

is_prime := FALSE; -- Mark as not prime if divisible

EXIT; -- Exit the inner loop

END IF;

END LOOP;

-- If is_prime is still TRUE, print the number as prime

IF is_prime THEN

DBMS_OUTPUT.PUT_LINE(i || ' is a prime number'); -- Print the prime number

END IF;

END IF;

END LOOP; -- End of outer loop

END;
DEPARTMENT OF INFORMATION TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id:23202B0063

Practical No: 20
Title of Experiment Implement PL/SQL program using Sequential Control

X. Practical related questions


5. List Iterative statement in PL/SQL
Ans:
● loop
● For loop
● While loop

6. Write PL/SQL program using any one Iterative statement.


Ans: BEGIN
-- Loop to print numbers from 10 to 1

FOR i IN REVERSE 1..10 LOOP

DBMS_OUTPUT.PUT_LINE(i); -- Print the current number

END LOOP;

END;

XI. Exercise
7. Write a PL/SQL program to display multiplication table of 5 using FOR loop.
Ans:
BEGIN

FOR i IN 1..10 LOOP

DBMS_OUTPUT.PUT_LINE('5 x ' || i || ' = ' || (5 * i));

END LOOP;

END;
DEPARTMENT OF INFORMATION TECHNOLOGY

8. Write a PL/SQL program to calculate factorial of 10 by using PL/SQL WHILE LOOP


statement.
Ans:
DECLARE

num NUMBER := 10;

factorial NUMBER := 1;

i NUMBER := 1;

BEGIN

WHILE i <= num LOOP

factorial := factorial * i;

i := i + 1;

END LOOP;

DBMS_OUTPUT.PUT_LINE('Factorial of ' || num || ' is ' || factorial);

END;
DEPARTMENT OF INFORMATION TECHNOLOGY

9. Write a PL/SQL program to calculate the prime numbers between 1 to 50.

Ans:
DECLARE

i NUMBER; -- Variable to iterate through numbers

j NUMBER; -- Variable to check for factors

is_prime BOOLEAN; -- Flag to determine if a number is prime

BEGIN

-- Loop through numbers from 2 to 50

FOR i IN 2..50 LOOP

is_prime := TRUE; -- Assume the current number is prime

-- Check if the number is 2 (the only even prime)

IF i = 2 THEN

DBMS_OUTPUT.PUT_LINE(i || ' is a prime number'); -- Print 2 as prime

ELSE

-- Loop through numbers from 2 to half of i to check for factors

FOR j IN 2..i/2 LOOP

-- Check if i is divisible by j

IF MOD(i, j) = 0 THEN

is_prime := FALSE; -- Mark as not prime if divisible

EXIT; -- Exit the inner loop


DEPARTMENT OF INFORMATION TECHNOLOGY
END IF;

END LOOP;

-- If is_prime is still TRUE, print the number as prime

IF is_prime THEN

DBMS_OUTPUT.PUT_LINE(i || ' is a prime number'); -- Print the prime number

END IF;

END IF;

END LOOP; -- End of outer loop

END;
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject: Database Management System Subject Code: 313315
Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Roll Id:

Practical No: 21
Title of Experiment Create Implicit and Explicit Cursors.
Cursors are used to handle multiple rows efficiently by fetching and
processing one row at a time in a PL/SQL program.
X. Practical related questions
1. Distinguish between Implicit and Explicit cursors in oracle.
Ans:
Feature Implicit Cursor Explicit Cursor

Definition Automatically created by Oracle for Defined explicitly by the


SQL statements like SELECT INTO, programmer for handling
INSERT, UPDATE, and DELETE. queries that return multiple
rows.
Control Oracle controls the lifecycle of The programmer has complete
implicit cursors. control over the cursor's
lifecycle (open, fetch, close).
Handling multiple Can handle only single-row queries. Can handle both single-row
rows and multi-row queries.
Cursor Name No name is assigned; it's managed The programmer assigns a
internally by Oracle. name to the cursor
Error Handling Raises an exception automatically if Must handle exceptions
no rows are returned. manually if required.

2. List advantages of using cursors in SQL programming.


Ans:
• Handle multiple rows: Cursors allow you to process query results that return
more than one row, one at a time.
• Control query processing: You can fetch, skip, or process rows as needed,
giving you more control over the data.
• Easier to manage data: Cursors make it easier to work with large datasets by
handling them in manageable parts.
• Reduces complexity: They simplify code by breaking down complex query
results into smaller steps.
• Error handling: Cursors help detect and handle errors during data retrieval or
processing.
• Memory efficiency: They allow gradual fetching of data, which can save
memory for large result sets.

XI. Exercise
DEPARTMENT OF INFORMATION TECHNOLOGY
1. Write a PL/SQL program for displaying details of students studying in
computer department using cursors.
Ans:

Step 1:
Create table called students and Insert 7 records to execute cursor program

CREATE TABLE students (


id NUMBER(5), -- Unique ID for each student
sname VARCHAR2(50), -- Student's name
department VARCHAR2(20) -- Department name
);

Output:

INSERT INTO students VALUES (1, 'Aarav', 'computer');


INSERT INTO students VALUES (2, 'Vihaan', 'Electronics');
INSERT INTO students VALUES (3, 'Isha', 'computer');
INSERT INTO students VALUES (4, 'Riya', 'Mechanical');
INSERT INTO students VALUES (5, 'Aditya', 'computer');
INSERT INTO students VALUES (6, 'Mira', 'Civil');
INSERT INTO students VALUES (7, 'Nikhil', 'computer');

Step 2:
DECLARE
CURSOR comp_dept_cursor IS
SELECT * FROM students WHERE department = 'computer';
student_row students%ROWTYPE;
BEGIN
OPEN comp_dept_cursor;
LOOP
FETCH comp_dept_cursor INTO student_row;
EXIT WHEN comp_dept_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('ID: ' || student_row.id || ', Name: ' || student_row.name);
DEPARTMENT OF INFORMATION TECHNOLOGY
END LOOP;
CLOSE comp_dept_cursor;
END;Output:

2. Write a PL/SQL program to print even number of records stored in the


student table.
Ans:

Step 1:
Create table students and insert 7 to 8 rows(which is done already in the earlier
question)

Step 2:
DECLARE
CURSOR even_cursor IS
SELECT * FROM students WHERE MOD(id, 2) = 0;
student_row students%ROWTYPE;
BEGIN
OPEN even_cursor;
LOOP
FETCH even_cursor INTO student_row;
EXIT WHEN even_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('ID: ' || student_row.id || ', Name: ' ||
student_row.name);
END LOOP;
CLOSE even_cursor;
END;

Output:
DEPARTMENT OF INFORMATION TECHNOLOGY

3. Write a PL/SQL program to display the number of items having price more
than 10000 in store table using cursors.
Ans:

Step 1:

Create table called store and Insert 7 records to execute cursor program

CREATE TABLE store (


id NUMBER (5), -- Unique ID for each item
item_name VARCHAR2(50), -- Name of the item
price NUMBER(10, 2) -- Price of the item
);

Output:
DEPARTMENT OF INFORMATION TECHNOLOGY
INSERT INTO store VALUES (1, 'Laptop', 45000);
INSERT INTO store VALUES (2, 'Mobile Phone', 8000);
INSERT INTO store VALUES (3, 'Tablet', 12000);
INSERT INTO store VALUES (4, 'Washing Machine', 18000);
INSERT INTO store VALUES (5, 'Smart TV', 32000);
INSERT INTO store VALUES (6, 'Headphones', 3000);
INSERT INTO store VALUES (7, 'Refrigerator', 25000);

Step 2:
DECLARE
CURSOR price_cursor IS
SELECT COUNT(*) AS item_count FROM store WHERE price > 10000;
item_count NUMBER;
BEGIN
OPEN price_cursor;
FETCH price_cursor INTO item_count;
DBMS_OUTPUT.PUT_LINE('Number of items with price > 10000: ' || item_count);
CLOSE price_cursor;
END;

Output:
DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id:23202B0063

Practical No: 22
Title of Experiment Implement PL/SQL program based on Exception Handling (Pre-
defined exceptions) application
X. Practical related questions
1. Distinguish between user defined exception and predefined exception
Ans:

Feature User-Defined Exception Predefined Exception


Definition Custom exceptions explicitly defined Built-in exceptions
by the programmer. provided by Oracle for
common errors.
When it is raised ? Raised manually using the RAISE Automatically raised by
statement. Oracle when specific errors
occur.
Example RAISE_APPLICATION_ERROR or a NO_DATA_FOUND,
custom condition. TOO_MANY_ROWS,
ZERO_DIVIDE.
Declaration Must be declared in the PL/SQL block Automatically available, no
or package. need for explicit
declaration.
Error Codes Custom error numbers range from - Associated with standard
20000 to -20999. Oracle error codes (e.g.,
ORA-01403 for
NO_DATA_FOUND).

2. Explain pre-defined exception with an example.


Ans:

Predefined exceptions are built-in errors in Oracle that occur automatically when certain
problems happen during PL/SQL execution. They help handle common issues without needing
to write custom error handling code.

Example:

• One common predefined exception is NO_DATA_FOUND.

• This occurs when a SELECT INTO statement does not return any rows.
DEPARTMENT OF INFORMATION TECHNOLOGY
Simple Code Example:

DECLARE

student_name VARCHAR2(50);

BEGIN

-- Trying to find a student with ID 10

SELECT name INTO student_name FROM students WHERE id = 10;

DBMS_OUTPUT.PUT_LINE('Student Name: ' || student_name);

EXCEPTION

WHEN NO_DATA_FOUND THEN

DBMS_OUTPUT.PUT_LINE('No student found with this ID.');

END;

Explanation:

• In this example, if there is no student with ID 10, the NO_DATA_FOUND exception is raised.
• The program catches this error and prints "No student found with this ID" instead of crashing.

This way, predefined exceptions help manage errors smoothly in PL/SQL.

XI. Exercise

1. Write a PL/SQL program that asks the user to input two numbers and divide the first
number by the second. Handle the predefined exception for division by zero and
display an appropriate message if it occurs.
Ans:

DECLARE

num1 NUMBER;

num2 NUMBER;

result NUMBER;

BEGIN

-- Asking the user for input


DEPARTMENT OF INFORMATION TECHNOLOGY
DBMS_OUTPUT.PUT_LINE('Enter the first number:');

num1 := &first_number; -- Use substitution variable for input

DBMS_OUTPUT.PUT_LINE('Enter the second number:');

num2 := &second_number; -- Use substitution variable for input

-- Division operation

result := num1 / num2;

DBMS_OUTPUT.PUT_LINE('Result: ' || result);

EXCEPTION

WHEN ZERO_DIVIDE THEN

DBMS_OUTPUT.PUT_LINE('Error: Division by zero is not allowed.');

END;

OR

DECLARE

num1 NUMBER :=10;

num2 NUMBER :=0;

result NUMBER;

BEGIN

-- Division operation

result := num1 / num2;

DBMS_OUTPUT.PUT_LINE('Result: ' || result);

EXCEPTION

WHEN ZERO_DIVIDE THEN

DBMS_OUTPUT.PUT_LINE('Error: Division by zero is not allowed.');

END;
DEPARTMENT OF INFORMATION TECHNOLOGY
Output:

2.Write a PL/SQL program that retrieves the salary of an employee based on their
employee ID (emp_id). If the employee ID does not exist in the database, handle the
NO_DATA_FOUND exception and print a message saying, "Employee ID not found."
Ans:

Step 1:

Create table called emp and insert rows in emp table

CREATE TABLE emp (

empno NUMBER(4) PRIMARY KEY, -- Employee Number

ename VARCHAR2(10), -- Employee Name

job VARCHAR2(9), -- Job Title

mgr NUMBER(4), -- Manager's Employee Number

hiredate DATE, -- Hire Date

sal NUMBER(7, 2), -- Salary

comm NUMBER(7, 2), -- Commission

deptno NUMBER(2) -- Department Number

);

Output:
DEPARTMENT OF INFORMATION TECHNOLOGY

INSERT INTO emp VALUES (7839, 'KING', 'President', NULL, '17-JUN-1981', 5000, NULL, 10);
INSERT INTO emp VALUES (7566, 'JONES', 'Manager', 7839, '21-JUN-1981', 2975, NULL, 10);
INSERT INTO emp VALUES (7698, 'BLAKE', 'Manager', 7839, '30-JUN-1981', 2850, NULL, 30);
INSERT INTO emp VALUES (7782, 'CLARK', 'Manager', 7839, '14-JUN-1981', 2450, NULL, 10);
INSERT INTO emp VALUES (7788, 'SCOTT', 'Analyst', 7566, '18-JUN-1981', 3000, NULL, 10);
INSERT INTO emp VALUES (7900, 'JAMES', 'Clerk', 7698, '01-JUN-1981', 950, NULL, 30);
INSERT INTO emp VALUES (7844, 'TURNER', 'Salesman', 7698, '01-JUN-1981', 1500, 0, 30);
INSERT INTO emp VALUES (7902, 'FORD', 'Analyst', 7566, '01-JUN-1981', 3000, NULL, 20);
INSERT INTO emp VALUES (7654, 'MARTIN', 'Salesman', 7698, '01-JUN-1981', 1250, 1400, 30);
INSERT INTO emp VALUES (7499, 'ALLEN', 'Salesman', 7698, '01-JUN-1981', 1600, 300, 30);
INSERT INTO emp VALUES (7521, 'WARD', 'Salesman', 7698, '01-JUN-1981', 1250, 500, 30);

Step 2:

DECLARE

emp_id NUMBER := &employee_id; -- Use substitution variable for input

emp_salary NUMBER;

BEGIN

-- Retrieving the salary of the employee

SELECT salary INTO emp_salary FROM emp WHERE id = emp_id;

DBMS_OUTPUT.PUT_LINE('Salary of Employee ID ' || emp_id || ': ' || emp_salary);

EXCEPTION

WHEN NO_DATA_FOUND THEN


DEPARTMENT OF INFORMATION TECHNOLOGY
DBMS_OUTPUT.PUT_LINE('Employee ID not found.');

END;

Output:
DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF3K-B
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id: 23202B0063

Practical No: 23
Title of Experiment Implement PL/SQL program based on Exception Handling
(User-defined exceptions) application
X. Practical related questions
1. How to define the exception?
Ans:
Feature User-Defined Exception Predefined Exception
Definition Exceptions defined by the user Built-in exceptions provided by
for specific error handling. Oracle for common errors.
Steps to Define 1. Declare the exception in the 1.No declaration needed.
PL/SQL block.
2. Use the RAISE statement to 2.Automatically raised by
raise the exception when Oracle when errors occur.
needed.
3. Handle the exception in the 3.Handle in the EXCEPTION
EXCEPTION block. block if needed.

User-Defined Exception Example:

DECLARE
custom_exception EXCEPTION; -- Step 1: Declare the user-defined exception
emp_salary NUMBER := 1500; -- Sample salary
BEGIN
-- Check if salary is below a certain threshold
IF emp_salary < 2000 THEN
RAISE custom_exception; -- Step 2: Raise the exception
END IF;
EXCEPTION
WHEN custom_exception THEN
DBMS_OUTPUT.PUT_LINE('Salary is too low.'); -- Step 3: Handle the exception
END;
DEPARTMENT OF INFORMATION TECHNOLOGY

Pre-Defined Exception Example:


DECLARE
emp_salary NUMBER; -- Variable to store salary
BEGIN
-- Trying to find salary for employee ID 999 (assuming it does not exist)
SELECT salary INTO emp_salary FROM employees WHERE id = 999;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee ID not found.'); -- Handling the predefined exception
END;
/

2. Create the Procedure with the help of user defined exception.


Ans:
CREATE OR REPLACE PROCEDURE check_salary(salary IN NUMBER) IS
-- Step 1: Declare the user-defined exception
low_salary EXCEPTION;

BEGIN
-- Check if the salary is below 2000
IF salary < 2000 THEN
RAISE low_salary; -- Step 2: Raise the exception
END IF;
-- If salary is acceptable
DBMS_OUTPUT.PUT_LINE('Salary is acceptable: ' || salary);

EXCEPTION
-- Step 3: Handle the user-defined exception
WHEN low_salary THEN
DBMS_OUTPUT.PUT_LINE('Error: Salary is too low.');
END check_salary;
call the procedure like this:
BEGIN
check_salary(1500); -- You can change 1500 to test with different salary values
END;

XI. Exercise
DEPARTMENT OF INFORMATION TECHNOLOGY
1. Write a PL/SQL program by using the user defined exception.
Ans:
-- Simple PL/SQL Program to Multiply Two Digits
DECLARE
-- Step 1: Declare the user-defined exception
zero_digit EXCEPTION;

-- Variables to hold the two digits


num1 NUMBER;
num2 NUMBER;
result NUMBER;

BEGIN
-- Prompt user to enter two digits
num1 := &num1; -- First digit
num2 := &num2; -- Second digit

-- Check if either digit is zero


IF num1 = 0 OR num2 = 0 THEN
RAISE zero_digit; -- Step 2: Raise the exception
END IF;

-- Calculate the multiplication


result := num1 * num2;

-- Display the result


DBMS_OUTPUT.PUT_LINE('Result of multiplication: ' || result);

EXCEPTION
-- Step 3: Handle the user-defined exception
WHEN zero_digit THEN
DBMS_OUTPUT.PUT_LINE('Error: Do not enter zero.');
END;

2. Write a PL/SQL program that asks for customer Id, when user enters invalid Id, the
exception Invalid-Id is raised.
Ans:
Step 1:
Create table of customers and insert some records and then execute PL/SQL code

CREATE TABLE customers (


customer_id NUMBER PRIMARY KEY,
customer_name VARCHAR2(50),
email VARCHAR2(100),
phone_number VARCHAR2(15),
address VARCHAR2(100)
);
DEPARTMENT OF INFORMATION TECHNOLOGY

INSERT INTO customers VALUES (1, 'Aarav', 'aarav@example.com', '9876543210', 'Mumbai,


Maharashtra');
INSERT INTO customers VALUES (2, 'Vivaan', 'vivaan@example.com', '8765432109', 'Pune,
Maharashtra');
INSERT INTO customers VALUES (3, 'Aditya', 'aditya@example.com', '7654321098',
'Nagpur, Maharashtra');
INSERT INTO customers VALUES (4, 'Vihaan', 'vihaan@example.com', '6543210987',
'Nashik, Maharashtra');
INSERT INTO customers VALUES (5, 'Arjun', 'arjun@example.com', '5432109876',
'Aurangabad, Maharashtra');
INSERT INTO customers VALUES (6, 'Sai', 'sai@example.com', '4321098765', 'Thane,
Maharashtra');
INSERT INTO customers VALUES (7, 'Kabir', 'kabir@example.com', '3210987654',
'Kolhapur, Maharashtra');
INSERT INTO customers VALUES (8, 'Reyansh', 'reyansh@example.com', '2109876543',
'Solapur, Maharashtra');

Step 2 :
-- Simple PL/SQL Program to Check Customer ID
DECLARE
-- Step 1: Declare the user-defined exception
invalid_id EXCEPTION;

-- Variable to hold the customer ID


DEPARTMENT OF INFORMATION TECHNOLOGY
cust_id NUMBER;

-- Variable to hold the count of valid IDs


valid_count NUMBER;
BEGIN
-- Prompt user to enter a customer ID
cust_id := &cust_id; -- Example: Use '&cust_id' to prompt for input

-- Check if the customer ID exists in the customers table


SELECT COUNT(*)
INTO valid_count
FROM customers
WHERE customer_id = cust_id;

-- Raise an exception if no records found for the given ID


IF valid_count = 0 THEN
RAISE invalid_id; -- Step 2: Raise the exception
END IF;

-- If ID is valid
DBMS_OUTPUT.PUT_LINE('Valid Customer ID: ' || cust_id);

EXCEPTION
-- Step 3: Handle the user-defined exception
WHEN invalid_id THEN
DBMS_OUTPUT.PUT_LINE('Error: Invalid Customer ID.');
END;
DEPARTMENT OF INFORMATION TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF34K-B
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Pranav Phanse Roll Id: 23202B0063

Practical No: 24
Title of Experiment Create Procedures and stored procedures for modularity
X. Practical related questions
1. Write syntax for creating PL/SQL Procedure.
Ans:
CREATE OR REPLACE PROCEDURE procedure_name
(parameter1_name parameter1_type [IN | OUT | IN OUT],
parameter2_name parameter2_type [IN | OUT | IN OUT], ... )
IS
-- Declaration Section
BEGIN
-- Executable Section
-- PL/SQL statements
END procedure_name;

2. Write steps to call a procedure in PL/SQL


Ans:
Steps to Call a Procedure in Oracle PL/SQL
Direct Call:

You can directly call the procedure by its name.

EXECUTE procedure_name(parameter1_value, parameter2_value, ...);

Anonymous Block:

You can call the procedure within an anonymous PL/SQL block.

BEGIN
procedure_name(parameter1_value, parameter2_value, ...);
END;

3. List types of parameters in Procedure and explain them.


Ans:

Types of Parameters in Oracle SQL Procedures


• IN Parameter:

Description: Passes values to the procedure; the procedure can read but not modify them.
Example: Passing a student's name to display it.
DEPARTMENT OF INFORMATION TECHNOLOGY

• OUT Parameter:
Description: Returns values from the procedure; the procedure can modify the value.
Example: Calculating and returning a student's total marks.

• IN OUT Parameter:

Description: Reads and modifies the value; the modified value is accessible after execution.
Example: Updating an account balance after applying interest.

XI. Exercise
1. Write a procedure emp_count () to count number of employees in department, use
dept_no as input parameter
Ans:
Step 1:
CREATE TABLE employees
( ename VARCHAR2(50),
dname VARCHAR2(50),
job VARCHAR2(50),
empno NUMBER,
hiredate VARCHAR2(10),
loc VARCHAR2(50) );

INSERT INTO employees VALUES ('ADAMS', 'RESEARCH', 'CLERK', 7876, '23-MAY-87',


'DALLAS');
INSERT INTO employees VALUES ('ALLEN', 'SALES', 'SALESMAN', 7499, '20-FEB-81',
'CHICAGO');
INSERT INTO employees VALUES ('BLAKE', 'SALES', 'MANAGER', 7698, '01-MAY-81',
'CHICAGO');
INSERT INTO employees VALUES ('CLARK', 'ACCOUNTING', 'MANAGER', 7782, '09-JUN-81',
'NEW YORK');
INSERT INTO employees VALUES ('FORD', 'RESEARCH', 'ANALYST', 7902, '03-DEC-81',
'DALLAS');
INSERT INTO employees VALUES ('JAMES', 'SALES', 'CLERK', 7900, '03-DEC-81', 'CHICAGO');
DEPARTMENT OF INFORMATION TECHNOLOGY
INSERT INTO employees VALUES ('JONES', 'RESEARCH', 'MANAGER', 7566, '02-APR-81',
'DALLAS');
INSERT INTO employees VALUES ('KING', 'ACCOUNTING', 'PRESIDENT', 7839, '17-NOV-81',
'NEW YORK');
INSERT INTO employees VALUES ('MARTIN', 'SALES', 'SALESMAN', 7654, '28-SEP-81',
'CHICAGO');
INSERT INTO employees VALUES ('MILLER', 'ACCOUNTING', 'CLERK', 7934, '23-JAN-82', 'NEW
YORK');
INSERT INTO employees VALUES ('SCOTT', 'RESEARCH', 'ANALYST', 7788, '19-APR-87',
'DALLAS');
INSERT INTO employees VALUES ('SMITH', 'RESEARCH', 'CLERK', 7369, '17-DEC-80',
'DALLAS');
INSERT INTO employees VALUES ('TURNER', 'SALES', 'SALESMAN', 7844, '08-SEP-81',
'CHICAGO');
INSERT INTO employees VALUES ('WARD', 'SALES', 'SALESMAN', 7521, '22-FEB-81',
'CHICAGO');

Step 2:
CREATE OR REPLACE PROCEDURE emp_count (dept_no IN NUMBER) IS

emp_count_value NUMBER;

BEGIN

SELECT COUNT(*) INTO emp_count_value

FROM employees

WHERE DEPT_NO = dept_no;

DBMS_OUTPUT.PUT_LINE('Number of employees in department ' || dept_no || ': ' ||


emp_count_value);

END ;
DEPARTMENT OF INFORMATION TECHNOLOGY

Step 3:
Calling emp_count Procedure
DECLARE
dept_number NUMBER := 10; -- Specify the department number
BEGIN
emp_count(dept_number); -- Call the procedure
END;

2. Create a stored procedure to accept name and greet user with name.
Ans:
Step 1:
CREATE OR REPLACE PROCEDURE greet_user (user_name IN VARCHAR2) IS

BEGIN

DBMS_OUTPUT.PUT_LINE('Hello, ' || user_name || '!');

END;
DEPARTMENT OF INFORMATION TECHNOLOGY

Step 2:
Calling greet_user Procedure

DECLARE
user_name VARCHAR2(50) := 'Prerana'; -- Specify the user name
BEGIN
greet_user(user_name); -- Call the procedure
END;

3. Write a PL/SQL procedure to insert any three records in EMP table.


Ans:
Step 1:
CREATE TABLE emp
( empno NUMBER(10) ,
ename VARCHAR2(50),
deptno NUMBER(10));
DEPARTMENT OF INFORMATION TECHNOLOGY

Step 2:

CREATE OR REPLACE PROCEDURE insert_emp_records IS

BEGIN

INSERT INTO EMP VALUES (1, 'Alice', 10);

INSERT INTO EMP VALUES (2, 'John', 20);

INSERT INTO EMP VALUES (3, 'Charlie', 30);

COMMIT; -- Make sure to commit the changes

END ;

Step 3:
Calling insert_emp_records Procedure

BEGIN
insert_emp_records(); -- Call the procedure to insert records
END;
DEPARTMENT OF INFORMATION TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Roll Id:

Practical No: 25
Title of Experiment Create functions for given database

X. Practical related questions


1. What is the difference between Function and Procedure.
Ans:
Feature Function Procedure
Purpose Computes and returns a single value Performs a specific action or task
Return Must return a value Does not return a value
Type
Call Can be called within SQL statements Called using an anonymous block
Method or EXECUTE
Parameters Can have only IN parameters Can have IN, OUT, or IN OUT
parameters
Usage in Can be used in SELECT, WHERE, and Cannot be used directly in SQL
SQL other clauses statements
Syntax CREATE OR REPLACE CREATE OR REPLACE
FUNCTION function_name PROCEDURE procedure_name

(parameter1_name parameter1_type, ...) (parameter1_name


parameter1_type, ...)
RETURN return_type IS

BEGIN IS

-- Function body BEGIN

RETURN value; -- Procedure body


END function_name;
END procedure_name;

Example CREATE OR REPLACE FUNCTION CREATE OR REPLACE


add_numbers PROCEDURE greet_user
IS
(a IN NUMBER, b IN NUMBER) BEGIN
RETURN NUMBER
DBMS_OUTPUT.PUT_LINE('He
IS llo, User!');
BEGIN END greet_user;
DEPARTMENT OF INFORMATION TECHNOLOGY
RETURN a + b;

END add_numbers;

2. Write syntax for creating and replacing function.


Ans:

CREATE OR REPLACE
FUNCTION function_name

(parameter1_name parameter1_type, ...)

RETURN return_type IS

BEGIN

-- Function body

RETURN value;

END function_name;

XI. Exercise
1. Write PL/SQL function which will compute and return the maximum of two values.
Ans:
CREATE OR REPLACE FUNCTION max_of_two (a IN NUMBER, b IN NUMBER)
RETURN NUMBER IS

BEGIN

IF a > b THEN

RETURN a;

ELSE

RETURN b;

END IF;

END;
DEPARTMENT OF INFORMATION TECHNOLOGY

Calling Function in PL/SQL Program


DECLARE

value1 NUMBER := 15; -- First value

value2 NUMBER := 20; -- Second value

max_value NUMBER; -- Variable to hold the maximum value

BEGIN

max_value := max_of_two(value1, value2); -- Call the function

DBMS_OUTPUT.PUT_LINE('Maximum of ' || value1 || ' and ' || value2 || ' is: ' ||
max_value);

END;
DEPARTMENT OF INFORMATION TECHNOLOGY

Calling Function in SQL SELECT Statement

SELECT max_of_two(15, 20) AS max_value FROM dual;

2. Write PL/SQL function to calculate the factorial of given no.


Ans:
CREATE OR REPLACE FUNCTION factorial (n IN NUMBER)
RETURN NUMBER IS

fact NUMBER := 1;

BEGIN

FOR i IN 1..n LOOP

fact := fact * i;

END LOOP;

RETURN fact;

END factorial;
DEPARTMENT OF INFORMATION TECHNOLOGY

Calling Function in PL/SQL Program


DECLARE

number_value NUMBER := 5; -- Specify the number

fact_value NUMBER; -- Variable to hold the factorial value

BEGIN

fact_value := factorial(number_value); -- Call the function

DBMS_OUTPUT.PUT_LINE('Factorial of ' || number_value || ' is: ' || fact_value);

END;

Calling Function in SQL SELECT Statement


DEPARTMENT OF INFORMATION TECHNOLOGY
SELECT factorial(5) AS factorial_value FROM dual;
DEPARTMENT OF INFORMATION TECHNOLOGY
Subject: Database Management System Subject Code: 313315
Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Student: Roll Id:

Practical No: 26
Title of Experiment Implement triggers for given database

X. Practical related questions


1. Differentiate between row level trigger and statement level trigger
Ans

Feature Row-Level Trigger Statement-Level Trigger


Invocation Executes for each row Executes once for the entire
affected by the DML SQL statement
operation
Context Can access each individual Cannot access individual
row's old and new values rows
Performance Can be slower for large data Generally faster since it
changes due to multiple executes only once
executions
Use Cases Used for validations or Used for actions that apply to
operations on each row, like the entire statement, like
checking individual values logging or auditing

2. What is the purpose of using WHEN clause in a trigger


Ans:
• Conditional Execution: The WHEN clause allows you to specify conditions under which
the trigger should fire.
• Performance Optimization: It helps avoid unnecessary trigger executions, improving
overall performance.
• Specific Actions: Enables triggering actions only for specific scenarios, like checking
values or states.
• Better Control: Provides finer control over trigger behavior based on the data being
processed.
• Simplicity: Keeps the trigger logic cleaner and easier to understand by focusing only on
relevant situations.

XI. Exercise
1. Create a trigger on EMP table which is invoked when salary is below 5000 .
Ans:

Step 1:
-- Create the EMP table with specified columns
CREATE TABLE EMP (
EMPNO NUMBER PRIMARY KEY,
DEPARTMENT OF INFORMATION TECHNOLOGY
ENAME VARCHAR2(10),
SAL NUMBER
);

-- Insert sample data into the EMP table


INSERT INTO EMP VALUES (7369, 'SMITH', 800);
INSERT INTO EMP VALUES (7499, 'ALLEN', 1600);
INSERT INTO EMP VALUES (7521, 'WARD', 1250);
INSERT INTO EMP VALUES (7566, 'JONES', 2975);
INSERT INTO EMP VALUES (7654, 'MARTIN', 1250);
INSERT INTO EMP VALUES (7698, 'BLAKE', 2850);
INSERT INTO EMP VALUES (7782, 'CLARK', 2450);
INSERT INTO EMP VALUES (7788, 'SCOTT', 3000);
INSERT INTO EMP VALUES (7839, 'KING', 5000);
INSERT INTO EMP VALUES (7844, 'TURNER', 1500);
INSERT INTO EMP VALUES (7876, 'ADAMS', 1100);
INSERT INTO EMP VALUES (7900, 'JAMES', 950);
INSERT INTO EMP VALUES (7902, 'FORD', 3000);
INSERT INTO EMP VALUES (7934, 'MILLER', 1300);

Step 2:
CREATE OR REPLACE TRIGGER salary_check

BEFORE INSERT OR UPDATE ON EMP

FOR EACH ROW

BEGIN

IF :NEW.salary < 5000 THEN

DBMS_OUTPUT.PUT_LINE('Warning: Salary below 5000 for employee ' ||


:NEW.EMP_ID);

END IF;
DEPARTMENT OF INFORMATION TECHNOLOGY
END ;

Step 3:
Check if salary_check is fired or not:

1. SQL Statement to Check Trigger with INSERT

INSERT INTO EMP VALUES (102, 'John', 4000, 20);

2. SQL Statement to Check Trigger with UPDATE

UPDATE EMP
SET SAL = 4500
WHERE EMPNO = 102;

2. Create a trigger which invokes on updation of record in Department table


Ans:
Step 1:
create table department(
deptno number(2,0),
dname varchar2(14),
loc varchar2(13),
);
DEPARTMENT OF INFORMATION TECHNOLOGY

insert into department values(10, 'ACCOUNTING', 'NEW YORK');


insert into department values(20, 'RESEARCH', 'DALLAS');
insert into department values(30, 'SALES', 'CHICAGO');
insert into department values(40, 'OPERATIONS', 'BOSTON');

Step 2:
CREATE OR REPLACE TRIGGER department_update

AFTER UPDATE ON Department

FOR EACH ROW

BEGIN

DBMS_OUTPUT.PUT_LINE('Department record updated: Old Name = ' || :OLD.dept_name


|| ', New Name = ' || :NEW.dept_name);

END department_update;
DEPARTMENT OF INFORMATION TECHNOLOGY

Step 3:
Check if department_update is fired or not:

UPDATE Department

SET dname = 'Marketing'

WHERE deptno = 10;


DEPARTMENT OF INFORMATION TECHNOLOGY

Subject: Database Management System Subject Code: 313315


Semester: 3rd Course: IF4K-C
Laboratory No: L004C Name of Subject Teacher: Prerana
Jalgaonkar
Name of Students: Pranav Phanse Roll Id: 23202B0063
Tanmay Bhoir 23202B0064
Shravan Sawardekar 23202B0058

MICROPROJECT

1.What does the cursor do in the PL/SQL block, and how does it process and display the
data from the Passenger table?

Step1: Create a Table


CREATE TABLE Passenger
(
PassengerID NUMBER PRIMARY KEY,
FullName VARCHAR2(50) NOT NULL,
PhoneNumber VARCHAR2(15),
Gender CHAR(1) CHECK (Gender IN ('M', 'F', 'O')), -- M: Male, F: Female, O: Other
Nationality VARCHAR2(50)
);
OUTPUT:

Step2 : Insert 30 rows:


insert into passenger values(30,'Samika Kedekar',9999713244,'F','India')
insert into passenger values(29,'Gaurav Bhojane',9981713244,'M','India')
insert into passenger values(28,'Rajesh Pol',9991713244,'M','India')
insert into passenger values(27,'Atharv Gajula',7321713244,'M','India')
insert into passenger values(26,'Aaryan Patil',7321613244,'M','India')
DEPARTMENT OF INFORMATION TECHNOLOGY
insert into passenger values(25,'Deep Bhabhe',7521613244,'M','India')
insert into passenger values(24,'Chetan Patil',7521613243,'M','India')
insert into passenger values(23,'Chetan Patil',7521613243,'M','India')
insert into passenger values(23,'Yash Pawar',7521713243,'M','India')
insert into passenger values(22,'Suyash Thakur',7921713243,'M','India')
insert into passenger values(21,'Sanskar Mhatre',7921713143,'M','India')
insert into passenger values(20,'Sateesh Pawar',7921613143,'M','India')
insert into passenger values(19,'Guru Shinde',9921613143,'M','India')
insert into passenger values(18,'Virat Kohli',9923613143,'M','India')
insert into passenger values(17,'Siddesh Gawde',8923613143,'M','India')
insert into passenger values(16,'Vaishavi Gunjal',8923613143,'F','India')
insert into passenger values(15,'Samika Gawde',8723613143,'F','India')
insert into passenger values(14,'Aadesh Waykar',8723693143,'M','India')
insert into passenger values(13,'Pranav Kubal',8723583143,'M','India')
insert into passenger values(12,'Parth Phanse',9723583143,'M','India')
insert into passenger values(11,'Shravan Bhoir',9763583143,'M','India')
insert into passenger values(10,'Sachin Ramesh Tendulkar',976353143,'M','India')
insert into passenger values(9,'Kedar Jadhav',976553143,'M','India')
insert into passenger values(8,'Ravindra Jadeja',966553143,'M','India')
insert into passenger values(7,'Mahendra Singh Dhoni',966552143,'M','India')
insert into passenger values(6,'Pranav Phanse',9696552143,'M','India')
insert into passenger values(5,'Nagesh Gunjal',9756552143,'M','India')
insert into passenger values(4,'Shravani Sawardekar',9756552143,'F','India')
insert into passenger values(3,'Shravani Sawardekar',9756552143,'F','India')
insert into passenger values(3,'Rakhi Sawant',9756242143,'F','India')
insert into passenger values(2,'Raj Kadam',9656242143,'M','India')
insert into passenger values(1,'Ravi Sawant',9696582143,M,India)

Step3: Use cursor

DECLARE

CURSOR passenger_cursor IS
SELECT PassengerID, FullName, PhoneNumber, Gender, Nationality
FROM Passenger
ORDER BY FullName ASC;

passenger_record passenger_cursor%ROWTYPE;
BEGIN
OPEN passenger_cursor;
LOOP
FETCH passenger_cursor INTO passenger_record;

EXIT WHEN passenger_cursor%NOTFOUND;

DBMS_OUTPUT.PUT_LINE('ID: ' || passenger_record.PassengerID ||


', Name: ' || passenger_record.FullName ||
', Phone: ' || passenger_record.PhoneNumber ||
', Gender: ' || passenger_record.Gender ||
', Nationality: ' || passenger_record.Nationality);
END LOOP;
DEPARTMENT OF INFORMATION TECHNOLOGY
CLOSE passenger_cursor;
END;

Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy