ad3391 LAB MANUAL
ad3391 LAB MANUAL
NO:6
PLSQL PROGRAM TO FIND HIGHEST PAID EMPLOYEES
DATE:
Aim:
To write a PLSQL program to find the highest paid top five employees in an organization.
Algorithm:
1. Define the Data Structure:
o Ensure you have a table named employees (or similar) with relevant columns such as
employee_id, employee_name, and salary.
2. Create a Cursor:
o Define a cursor to select the top 5 highest-paid employees. This involves:
Ordering the employees by salary in descending order.
Limiting the results to the top 5 rows.
3. Open the Cursor:
o Initialize the cursor for processing.
4. Fetch Records:
o Loop through the cursor to fetch records one by one.
5. Process Each Record:
o For each fetched record, retrieve the employee details.
6. Handle Exceptions:
o Include error handling to manage any exceptions that might occur.
7. Close the Cursor:
o Ensure that the cursor is closed after processing to release resources.
8. Display Results:
o Use DBMS_OUTPUT.PUT_LINE to print the results.
Explanation:
Cursor Declaration:
top_employees_cursor selects the top 5 highest-paid employees. It uses an inner query to sort the
employees by salary in descending order and then applies ROWNUM to limit the result to the top 5.
Variables:
Variables v_employee_id, v_employee_name, and v_salary are used to store each employee's details
fetched from the cursor.
Cursor Processing:
Open the cursor and loop through the result set. For each record, fetch the employee details into the
defined variables and print them using DBMS_OUTPUT.PUT_LINE.
Exception Handling:
Basic exception handling is included to catch and report any errors that occur during the execution of
the PL/SQL block. It also ensures the cursor is closed if an error occurs.
Execution:
The / at the end of the block is used in SQL*Plus or Oracle SQL Developer to execute the PL/SQL
block.
PROGRAM:
CREATE TABLE employees1 ( employee_id NUMBER PRIMARY KEY, employee_name
VARCHAR2(100), salary NUMBER );
insert into employees1(employee_id,employee_name,salary)values(101,'abinesh',50000);
insert into employees1(employee_id,employee_name,salary)values(102,'bargavi',20000);
insert into employees1(employee_id,employee_name,salary)values(103,'chakkaravarthy',50000);
insert into employees1(employee_id,employee_name,salary)values(104,'daya',53000);
insert into employees1(employee_id,employee_name,salary)values(105,'ezhil',89000);
insert into employees1(employee_id,employee_name,salary)values(106,'fazil',65000);
insert into employees1(employee_id,employee_name,salary)values(107,'gayathri',56000);
insert into employees1(employee_id,employee_name,salary)values(108,'hari',10000);
insert into employees1(employee_id,employee_name,salary)values(109,'iniyan',15000);
DECLARE
-- Define a cursor to fetch the top 5 highest-paid employees
CURSOR top_employees_cursor IS
SELECT employee_id, employee_name, salary
FROM (
SELECT employee_id, employee_name, salary
FROM employees1
ORDER BY salary DESC
)
WHERE ROWNUM <= 5;
-- Define variables to hold employee data
v_employee_id employees1.employee_id%TYPE;
v_employee_name employees1.employee_name%TYPE;
v_salary employees1.salary%TYPE;
BEGIN
-- Open the cursor
OPEN top_employees_cursor;
DBMS_OUTPUT.PUT_LINE('TOP FIVE PAID EMPLOYEES');
-- Loop through the cursor and print the results
LOOP
FETCH top_employees_cursor INTO v_employee_id, v_employee_name, v_salary;
EXIT WHEN top_employees_cursor%NOTFOUND;
-- Output employee details
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || v_employee_id || ', Name: ' || v_employee_name ||
', Salary: ' || v_salary);
END LOOP;
-- Close the cursor
CLOSE top_employees_cursor;
EXCEPTION
WHEN OTHERS THEN
-- Handle any exceptions
DBMS_OUTPUT.PUT_LINE('An error has occurred: ' || SQLERRM);
IF top_employees_cursor%ISOPEN THEN
CLOSE top_employees_cursor;
END IF;
END;
/
OUTPUT:
Result:
Thus,the PLSQL program to find the highest paid top five employees in an organization is written
and executed successfully.
EX.NO:7
DATE:
PLSQL PROGRAM TO FIND SUM OF N NUMBERS
Aim:
To write a PLSQL program to find sum of N numbers.
Algorithm:
1. Create a Temporary Table: This will hold the numbers for which you want to find the sum.
2. Insert Numbers into the Table: Populate the table with the numbers.
3. Calculate the Sum: Compute the sum using an SQL query.
4. Display the Result: Output the sum using DBMS_OUTPUT.
Explanation:
1. Temporary Table Creation:
o temp_numbers is a global temporary table created for holding numbers. It’s created using
dynamic SQL (EXECUTE IMMEDIATE).
2. Insert Numbers:
o Numbers are inserted into the temp_numbers table. Modify these INSERT statements to add
your own numbers or data as needed.
3. Cursor for Data Fetching:
o num_cursor selects numbers from the temporary table. A loop is used to fetch and sum these
numbers.
4. Sum Calculation:
o The v_sum variable accumulates the total sum of numbers.
5. Exception Handling:
o Basic exception handling is included to handle cases like no data found or other errors.
6. Output:
o The result is displayed using DBMS_OUTPUT.PUT_LINE.
Program:
CREATE TABLE temp_numbers(tempvalue number);
INSERT INTO temp_numbers (tempvalue) VALUES (10);
INSERT INTO temp_numbers (tempvalue) VALUES (20);
INSERT INTO temp_numbers (tempvalue) VALUES (30);
INSERT INTO temp_numbers (tempvalue) VALUES (40);
INSERT INTO temp_numbers (tempvalue) VALUES (50);
DECLARE
-- Variables
v_sum NUMBER := 0; -- To store the sum of numbers
v_num_count NUMBER := 0; -- To store the count of numbers
-- Exception for empty list or other issues
no_data_found EXCEPTION;
-- Cursor to fetch numbers from the table
CURSOR num_cursor IS
SELECT tempvalue FROM temp_numbers;
BEGIN
OPEN num_cursor; -- Open cursor
-- Fetch and sum the numbers
LOOP
FETCH num_cursor INTO v_num_count;
EXIT WHEN num_cursor%NOTFOUND;
v_sum := v_sum + v_num_count;
END LOOP;
-- Close the cursor
CLOSE num_cursor;
-- Output the result
DBMS_OUTPUT.PUT_LINE('The sum of the numbers is: ' || v_sum);
EXCEPTION
WHEN no_data_found THEN
DBMS_OUTPUT.PUT_LINE('No data found in the temporary table.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error has occurred: ' || SQLERRM);
END;
/
Output:
The sum of the numbers is: 150
Result:
Thus, the PLSQL program to find sum of N numbers is written and executed successfully.
EX.NO:8
DATE:
CREATING A VIEW AND IMPLEMENTING
PRIVILEGES AND KEY CONSTRAINTS FOR A
BANKING SYSTEM
Aim:
To create tables for a customer applying for bank loan (employee, customer and loan) and perform
the following:
A. View the customer names whose account opening date from 01.06.2018 to till now.
B. View the details of a customer whose loan amount is greater than 100000 in Coimbatore branch.
C. Create a view for customer table in order to prevent modification.
Procedure and Program:
-- create employee table
CREATE TABLE employee (employee_id INT PRIMARY KEY, employee_name VARCHAR(20),
position VARCHAR(30));
insert into employee(employee_id,employee_name,position)values(101,'raj','manager');
insert into employee(employee_id,employee_name,position)values(102,'kumar','managing director');
insert into employee(employee_id,employee_name,position)values(103,'babu','cashier');
insert into employee(employee_id,employee_name,position)values(104,'abinay','assistant');
insert into employee(employee_id,employee_name,position)values(105,'chaaru','assistant manager');
select * from employee;
-------create customer table
CREATE TABLE customer (customer_id int PRIMARY KEY, customer_name VARCHAR(120),
account_opening_date DATE,branch_location VARCHAR(20));
insert into customer(customer_id,customer_name,account_opening_date,branch_location)
values(5001,'manish','2018-06-01','chennai');
insert into customer(customer_id,customer_name,account_opening_date,branch_location)
values(5002,'pradeesh','2018-08-02','mumbai');
insert into customer(customer_id,customer_name,account_opening_date,branch_location)
values(5003,'nithish','2007-07-01','bangalore');
insert into customer(customer_id,customer_name,account_opening_date,branch_location)
values(50004,'nithya','2021-07-01','bangalore');
insert into customer(customer_id,customer_name,account_opening_date,branch_location)
values(5102,'shriyas','2001-08-22','mangalore');
insert into customer(customer_id,customer_name,account_opening_date,branch_location)
values(5112,'shrimagizhan','2023-08-22','Coimbatore');
insert into customer(customer_id,customer_name,account_opening_date,branch_location)
values(5122,'diana','2023-08-22','Coimbatore');
select * from customer;
------create loan table
CREATE TABLE loan (loan_id int PRIMARY KEY,customer_id int,loan_amount int,branch_location
VARCHAR(20),FOREIGN KEY (customer_id) REFERENCES customer(customer_id));
insert into loan(loan_id,customer_id,loan_amount,branch_location)values(1001,5001,500000,'chennai');
insert into loan(loan_id,customer_id,loan_amount,branch_location)values(1002,5002,200000,'mumbai');
insert into loan(loan_id,customer_id,loan_amount,branch_location)values(1003,5003,70000,'bangalore');
insert into loan(loan_id,customer_id,loan_amount,branch_location)values(1004,5122,300000,'coimbatore');
select * from loan;
A. View the customer names whose account opening date from 01.06.2018 to till now.
CREATE VIEW recent_customers AS
SELECT customer_name
FROM customer
WHERE account_opening_date BETWEEN DATE '2018-06-01' AND SYSDATE();
-- Query the view to get customer names
SELECT * FROM recent_customers;
B. View the details of a customer whose loan amount is greater than 100000 in Coimbatore branch.
CREATE VIEW high_loan_customers AS
SELECT c.customer_id, c.customer_name, c.account_opening_date, l.loan_amount, l.branch_location
FROM customer c
JOIN loan l ON c.customer_id = l.customer_id
WHERE l.loan_amount > 100000 AND l.branch_location = 'Coimbatore';
-- Query the view to get customer details with high loan amounts in Coimbatore
SELECT * FROM high_loan_customers;
C. Create a View to Prevent Modification
To create a view that allows only read access to the customer table, preventing modifications:
-- Create a read-only view for the customer table
CREATE VIEW customer_read_only AS
SELECT customer_id, customer_name, account_opening_date, branch_location
FROM customer;
Output:
EMPLOYEE TABLE:+-------------+---------------+-------------------+
+---------------+
| customer_name |
+---------------+
| manish |
| pradeesh |
| shrimagizhan |
| diana |
| nithya |
+---------------+
Details of a customer whose loan amount is greater than 100000 in Coimbatore branch.
+-------------+---------------+----------------------+-------------+-----------------+
| customer_id | customer_name | account_opening_date | loan_amount | branch_location |
+-------------+---------------+----------------------+-------------+-----------------+
| 5122 | diana | 2023-08-22 | 300000 | coimbatore |
+-------------+---------------+----------------------+-------------+-----------------+
Read only view of customer table in order to prevent modification.
+-------------+---------------+----------------------+-----------------+
| customer_id | customer_name | account_opening_date | branch_location |
+-------------+---------------+----------------------+-----------------+
| 5001 | manish | 2018-06-01 | chennai |
| 5002 | pradeesh | 2018-08-02 | mumbai |
| 5003 | nithish | 2007-07-01 | bangalore |
| 5102 | shriyas | 2001-08-22 | mangalore |
| 5112 | shrimagizhan | 2023-08-22 | Coimbatore |
| 5122 | diana | 2023-08-22 | Coimbatore |
| 50004 | nithya | 2021-07-01 | bangalore |
+-------------+---------------+----------------------+-----------------+
Result:
Thus,the SQL queries implementing views,key constraints and privileges is executed successfully.
EX.NO:9
DCL AND TCL OPERATIONS
DATE:
Aim:
To create a database named College and its related tables (student, teacher, and management), and
then perform Data Control Language (DCL) and Transaction Control Language (TCL) operations,.
Procedure:
Step 1: Create Tables named student,teacher and management
Step 2: Perform Data Control Language (DCL) Operations
DCL operations manage permissions and access control to the database objects.
Grant Permissions
Granting SELECT, INSERT, UPDATE, and DELETE permissions to a user (e.g., user1) on the student table:
-- Grant permissions to user1 on student table
GRANT SELECT, INSERT, UPDATE, DELETE ON student TO user1;
-- Grant permissions to user1 on teacher table
GRANT SELECT ON teacher TO user1;
-- Grant permissions to user1 on management table
GRANT SELECT, UPDATE ON management TO user1;
Revoke Permissions
Revoking specific permissions from user1:
-- Revoke DELETE permission from user1 on student table
REVOKE DELETE ON student FROM user1;
-- Revoke SELECT permission from user1 on management table
REVOKE SELECT ON management FROM user1;
Step 3: Perform Transaction Control Language (TCL) Operations
TCL operations are used to manage transactions within a database.
Commit
To save the changes made during the current transaction:
-- Commit the current transaction
COMMIT;
Rollback
To undo changes made during the current transaction:
-- Rollback the current transaction
ROLLBACK;
Savepoint
To set a point within a transaction to which you can later roll back:
-- Set a savepoint named 'before_update'
SAVEPOINT before_update;
-- Rollback to the savepoint if needed
ROLLBACK TO SAVEPOINT before_update;
SQL commands for DCL OPERATIONS:
GRANT SELECT, INSERT, UPDATE, DELETE ON student TO system;
GRANT SELECT ON teacher TO system;
GRANT SELECT, UPDATE ON management TO system;
SQL commands for TCL OPERATIONS:
create table student(rollno number(10),name varchar(20));
insert into student(rollno,name)values(101,'AAA');
insert into student(rollno,name)values(102,'BBB');
insert into student(rollno,name)values(103,'CCC');
insert into student(rollno,name)values(104,'DDD');
insert into student(rollno,name)values(105,'EEE');
select * from student;
delete from student where rollno=102;
savepoint s2;
delete from student where rollno=103;
savepoint s3;
delete from student where rollno=104;
savepoint s4;
rollback to s4;
select * from student;
update student set rollno=102 where name ='EEE';
select * from student;
commit;
savepoint s5;
Output:
101|AAA
102|BBB
103|CCC
104|DDD
105|EEE
/Rolling back to s4/
101|AAA
105|EEE
/updating and committing the transaction/
101|AAA
102|EEE
Result:
Thus, the Data Control Language (DCL) and Transaction Control Language (TCL) operations is
performed successfully.
EX.NO:
PL/SQL PROCEDURE FOR DEPOSITS AND
DATE:
WITHDRAWAL IN A BANKING SYSTEM
Aim:
To write a PL/SQL Procedure for Deposits and Withdrawals in a Banking system.
Result:
Thus, the PL/SQL Procedure for Deposits and Withdrawals in a Banking system.is written and
executed successfully.
EX.NO:
Triggers
DATE:
Aim:
To implement trigger operation for the following:
1. Insert a new employee into the employee table.
2. Ensure that the emp_no of the new employee is not NULL.
3. If emp_no is not NULL, update the department table by adding the employee's salary to
the total_salary attribute of the corresponding department.
Procedure and Program:
The employee table has columns: emp_no, name, salary, dept_no.
The department table has columns: dept_no, dept_name, total_salary.
SQL Trigger
DELIMITER $$
CREATE TRIGGER after_employee_insert
AFTER INSERT ON employee
FOR EACH ROW
BEGIN
-- Check if the emp_no of the new employee is not null
IF NEW.emp_no IS NOT NULL THEN
-- Update the total_salary in the department table
UPDATE department
SET total_salary = total_salary + NEW.salary
WHERE dept_no = NEW.dept_no;
END IF;
END$$
DELIMITER ;
Explanation:
AFTER INSERT ON employee: The trigger is executed after a new row is inserted into the
employee table.
FOR EACH ROW: The trigger will run for each row that is inserted.
IF NEW.emp_no IS NOT NULL THEN: This checks if the emp_no of the new employee is not
NULL.
UPDATE department: The total_salary of the department related to the new employee is updated
by adding the employee's salary to it.
Result:
Thus, the above program is implemented using trigger function and it is executed successfully.
EX.NO:
IMPLEMENTING FUNCTION TO CALCULATE NET
DATE:
SALARY
Aim:
To create a function that calculates the net salary for all employees in an organization, and the net
salary is calculated by subtracting deductions (like taxes, insurance, etc.) from the gross salary.
Procedure and Program:
Create an employee table with the following structure:
emp_no: Employee Number
name: Employee Name
gross_salary: Gross Salary of the Employee
tax_deduction: Tax Deduction for the Employee
insurance_deduction: Insurance Deduction for the Employee
other_deduction: Any other deductions
SQL Function to Calculate Net Salary
DELIMITER $$
CREATE FUNC TION calculate_net_salary()
RETURNS TABLE (emp_no INT, name VARCHAR(255), net_salary DECIMAL(10, 2))
BEGIN
RETURN
SELECT
emp_no,
name,
(gross_salary - IFNULL(tax_deduction, 0) - IFNULL(insurance_deduction, 0) -
IFNULL(other_deduction, 0)) AS net_salary
FROM
employee;
END$$
DELIMITER ;
Usage:
Once you create this function, you can call it to get the net salary of all employees:
SELECT * FROM calculate_net_salary();
Explanation:
RETURNS TABLE (emp_no, name, net_salary): The function returns a table with the employee
number, name, and net salary.
IFNULL(deduction, 0): This function is used to ensure that if any deduction value is NULL, it is
treated as 0.
SELECT Statement: The function selects the emp_no, name, and calculates the net_salary by
subtracting all deductions from the gross_salary for each employee.
Result:
Thus, the function to calculate net salary is implemented and executed
successfully.
EX.NO:
PL/SQL PROGRAM TO IMPLEMENT PROCEDURE
DATE:
Aim:
To create a PL/SQL procedure that increments salaries for employees based on their experience.
Procedure:
Assumptions: Assume that the employee table has the following structure:
employee_id (primary key)
employee_name
experience_years (number of years of experience)
salary (current salary)
Procedure Requirements:
For employees with less than 5 years of experience, increment their salary by 2000.
For employees with 5 or more years of experience, increment their salary by 5000.
Program:
CREATE OR REPLACE PROCEDURE increment_salaries AS
BEGIN
-- Increment salary for employees with less than 5 years of experience
UPDATE employee
SET salary = salary + 2000
WHERE experience_years < 5;
Execution
To execute the procedure, you can use the following command in your SQL environment:
-- Call the procedure to update salaries
BEGIN
increment_salaries;
END;
/
Explanation:
1. Update Statement:
o The first UPDATE statement increases the salary by 2000 for employees with less than 5
years of experience.
o The second UPDATE statement increases the salary by 5000 for employees with 5 or more
years of experience.
2. Commit:
o COMMIT is used to save the changes to the database. This ensures that all updates made by
the procedure are permanently saved.
3. Exception Handling:
o If any error occurs during execution, the EXCEPTION block will handle it. The ROLLBACK
statement undoes any changes made if an error occurs, and an error message is printed using
DBMS_OUTPUT.PUT_LINE.
4. Output Message:
o DBMS_OUTPUT.PUT_LINE is used to print a success message or error message to indicate
the status of the procedure execution.
Result:
Thus,the PL/SQL program implementing procedure is written and executed
successfully.