Pranav Phanse 23202B0063
Pranav Phanse 23202B0063
Practical No: 2
Title of Experiment Create Database schema for given application
Note: Below are a few sample questions for reference. Teacher must design more
Ans:
Ans:
EMP(empno,ename,mgr,job,deptno,loc,dname)
XI. Exercise
How would you create a new database named 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);
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
Practical No: 3
Title of Execute DDL commands to manage Database using SQL
Experiment
Note: Below are few sample questions for reference. Teacher must design more such
questions so as to
(Note: Use Point VII and XIII to XV for all relevant practical exercise use blank pages
2. Create tables EMPLOYEE and DEPARTMENT with following schema by applying Primary
Ans:
Purpose Remove the entire table from the Remove all rows from a table
database
Rollback Command Rollback not applicable Rollback not applicable
Ans:
DEPARTMENT OF INFORMATION TECHNOLOGY
Describe command is used to view the structure of created table.
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.)
check constraint on percentage that the percentage should not be greater than 100.
Ans:
Studname varchar2(30),
Ans:
Ans:
1. Create table
Passenger_details(passenger_name varchar2(30),
train_details varchar2(30)
,travelling_date date,
birthdate date);
Output :
Practical No: 4
Title of Execute DML Commands to manipulate data using SQL
Experiment
Note: Below are a few sample questions for reference. Teacher must design more such
questions to ensure the achievement of identified CO.
3.Explain the differences between the DELETE, DROP, and TRUNCATE commands in
SQL.
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
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
Ans:
Syntax:
Select column1name,column2name from tablename;
Select empno,salary from emp;
DEPARTMENT OF INFORMATION TECHNOLOGY
Practical No: 5
Title of Execute DCL commands to control the access to data using SQL
Experiment
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.
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.)
Practical No: 7
Title of Write Queries using Arithmetic operators.
Experiment
Example
SELECT 2 + 3 * 4 - 5 / (1 + 1) FROM dual;
Result
SELECT 2 + 3 * 4 - 5 / (1 + 1) AS Result FROM dual;
-- Result: 11.5
Example 1 :
Select * from orders;
Example:
Select cust_id,amount from orders;
1)
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:
iv Display new column named half_amount which is divided by 2 to the amount field.
Ans:
Practical No: 8
Title of Apply built-in Logical operators on given data
Experiment
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;
XI. Exercise
Ans:
Ans:
Ans:
Ans:
City in (‘Mumbai’,’Pune’,’Nashik’,’Nagpur’);
Exercise
DEPARTMENT OF INFORMATION TECHNOLOGY
Practical No: 9
Title of Implement Relational operators to apply various conditions in
Experiment query.
XI. Exercise
i. Select stu_name, course_id, from Student WHERE percentage is >=60 and <=100;
Ans:
Or
ii. Select details of students whose Roll numbers are above 15;
Ans:
Ans:
Practical No: 10
Title of Experiment Use Set operators to perform different operations
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:
first_name
Aarav
Ananya
Ishaan
Priya
Rohan
Table: students_delhi
first_name
Aarav
Ananya
Ishaan
Priya
Rohit
Example:
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:
Example:
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:
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:
Example:
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
emp1(empno,ename,deptno)
emp2(empno,ename,deptno)
Table: emp1
Table: emp2
UNION ALL
UNION
INTERSECT
MINUS
Practical No: 11
Title of Experiment Execute queries using string functions
Example
SELECT REPLACE('Hello World', 'World', 'Everyone') FROM DUAL;
Output:
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:
Example:
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:
Output:
Output:
DEPARTMENT OF INFORMATION TECHNOLOGY
Output:
DEPARTMENT OF INFORMATION TECHNOLOGY
Practical No: 12
Title of Experiment Execute queries using Arithmetic functions
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
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
Ans 1. Addition(+)
2. Subtraction(-)
3. Division(/)
4. Multiplication(*)
XI. Exercise
Practical No: 13
Title of Experiment Implement queries using Date and Time functions
Syntax:
Select FORMAT(number, decimal_places) from dual;
Example:
SELECT FORMAT(1234.567, 2) FROM dual;
Example:
SELECT MONTHS_BETWEEN('2024-09-01', '2024-06-01') 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;
Practical No: 14
Title of Experiment Implement queries using Aggregate functions
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)
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:
Practical No: 15
Title of Experiment Execute queries for Ordering and Grouping data.
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)
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.
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)
XI. Exercise
Practical No: 16
Title of Experiment Implement SQL queries for Inner and Outer Join
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
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:
EMP Table:
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.
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.
Sample Output:
Here, the department Operations (deptno 40) has no employees, so empno and ename are NULL.
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.
Sample Output:
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.
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);
Ans:
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:
Practical No: 17
Title of Experiment Create and manage Views for faster access on relations.
Syntax:
Example:
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.
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)
);
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.
Ans:
ALTER SEQUENCE emp_sequence
INCREMENT BY 15
MAXVALUE 1000
CYCLE
CACHE 20;
Practical No: 18
Title of Experiment Implement PL/SQL program using Conditional Statements
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%)
Fail (<40)
Ans:
DECLARE
BEGIN
percentage := &user_input; -- Replace &user_input with the actual input method if needed
grade := 'Distinction';
ELSE
DEPARTMENT OF INFORMATION TECHNOLOGY
grade := 'Fail';
END IF;
END;
OR
DECLARE
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
Practical No: 19
Title of Experiment Implement PL/SQL program using Iterative Statements
END LOOP;
END;
XI. Exercise
4. Write a PL/SQL program to display multiplication table of 5 using FOR loop.
Ans:
BEGIN
END LOOP;
END;
DEPARTMENT OF INFORMATION TECHNOLOGY
factorial NUMBER := 1;
i NUMBER := 1;
BEGIN
factorial := factorial * i;
i := i + 1;
END LOOP;
END;
BEGIN
IF i = 2 THEN
ELSE
-- Check if i is divisible by j
IF MOD(i, j) = 0 THEN
END IF;
END LOOP;
IF is_prime THEN
END IF;
END IF;
END;
DEPARTMENT OF INFORMATION TECHNOLOGY
DEPARTMENT OF INFORMATION TECHNOLOGY
Practical No: 20
Title of Experiment Implement PL/SQL program using Sequential Control
END LOOP;
END;
XI. Exercise
7. Write a PL/SQL program to display multiplication table of 5 using FOR loop.
Ans:
BEGIN
END LOOP;
END;
DEPARTMENT OF INFORMATION TECHNOLOGY
factorial NUMBER := 1;
i NUMBER := 1;
BEGIN
factorial := factorial * i;
i := i + 1;
END LOOP;
END;
DEPARTMENT OF INFORMATION TECHNOLOGY
Ans:
DECLARE
BEGIN
IF i = 2 THEN
ELSE
-- Check if i is divisible by j
IF MOD(i, j) = 0 THEN
END LOOP;
IF is_prime THEN
END IF;
END IF;
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
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
Output:
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:
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
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
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:
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:
• 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
EXCEPTION
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.
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
-- Division operation
EXCEPTION
END;
OR
DECLARE
result NUMBER;
BEGIN
-- Division operation
EXCEPTION
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:
);
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_salary NUMBER;
BEGIN
EXCEPTION
END;
Output:
DEPARTMENT OF INFORMATION TECHNOLOGY
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.
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
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;
BEGIN
-- Prompt user to enter two digits
num1 := &num1; -- First digit
num2 := &num2; -- Second digit
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
Step 2 :
-- Simple PL/SQL Program to Check Customer ID
DECLARE
-- Step 1: Declare the user-defined exception
invalid_id EXCEPTION;
-- 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
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;
Anonymous Block:
BEGIN
procedure_name(parameter1_value, parameter2_value, ...);
END;
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) );
Step 2:
CREATE OR REPLACE PROCEDURE emp_count (dept_no IN NUMBER) IS
emp_count_value NUMBER;
BEGIN
FROM employees
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
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;
Step 2:
BEGIN
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
Practical No: 25
Title of Experiment Create functions for given database
BEGIN IS
END add_numbers;
CREATE OR REPLACE
FUNCTION function_name
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
BEGIN
DBMS_OUTPUT.PUT_LINE('Maximum of ' || value1 || ' and ' || value2 || ' is: ' ||
max_value);
END;
DEPARTMENT OF INFORMATION TECHNOLOGY
fact NUMBER := 1;
BEGIN
fact := fact * i;
END LOOP;
RETURN fact;
END factorial;
DEPARTMENT OF INFORMATION TECHNOLOGY
BEGIN
END;
Practical No: 26
Title of Experiment Implement triggers for given database
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
);
Step 2:
CREATE OR REPLACE TRIGGER salary_check
BEGIN
END IF;
DEPARTMENT OF INFORMATION TECHNOLOGY
END ;
Step 3:
Check if salary_check is fired or not:
UPDATE EMP
SET SAL = 4500
WHERE EMPNO = 102;
Step 2:
CREATE OR REPLACE TRIGGER department_update
BEGIN
END department_update;
DEPARTMENT OF INFORMATION TECHNOLOGY
Step 3:
Check if department_update is fired or not:
UPDATE Department
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?
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;
Output: