manual_mridul
manual_mridul
manual_mridul
LAB MANUAL
SUBMITTED BY :
NAME : MRIDUL RAJGARIA
REG NO : 23BCE11832
SLOT : C14+E11+E12
LAB ASSIGNMENTS:
S. ASSIGNMENT PAGE
NO. NO.
1) Delete duplicate row from the table. 1
2) Display the alternate row from table. 3
3) Delete alternate row from table. 5
4) Update multiple rows in using single update 7
statement.
5) Find the third highest paid and third lowest paid 9
salary.
6) Display the 3rd, 4th, 9th rows from table. 11
7) Display the ename, which is start with j, k, l or m. 13
8) Show all employees who were hired the first half of 15
the month.
9) Display the three record in the first row and two 17
records in the second row and one record
in the third row in a single SQL statements.
10) Write a SQL statements for rollback commit and save 19
points.
11) Write a pl/SQL for select, insert, update and delete 21
statements.
12) Write a pl/SQL block to delete a record. If delete 24
operation is successful return 1 else
return 0.
13) Display name, hire date of all employees using 26
cursors.
14) Display details of first 5 highly paid employees using 30
cursors.
S. ASSIGNMENT PAGE
NO. NO.
15) Write a database trigger which fires if you try to 33
insert, update, or delete after 7’o’ clock.
16) Write a data base trigger, which acts just like primary 36
key and does not allow duplicate
values.
17) Create a data base trigger, which performs the action 38
of the on delete cascade..
18) Write a data base trigger, which should not delete 40
from emp table if the day is Sunday.
1
Experiment 1
Deleting Duplicate Rows from the Table
Objective:
To remove duplicate rows from a table while retaining only unique records.
Theory:
Duplicate records in a database can result from various reasons like data
migration or errors in data entry. In SQL, we can identify duplicates based on a
set of columns and use the DELETE statement to remove them. A common
approach is using ROW_NUMBER() with a condition to keep the first
occurrence and delete the rest.
Experiment Procedure:
1. Create a database and a table with sample data.
2. Insert duplicate rows into the table.
3. Use a DELETE query to remove the duplicate records, keeping only one
instance of each record.
4. Verify that duplicates have been removed by running a SELECT query.
SQL Query:
DELETE FROM DETAILS
WHERE SN NOT IN (
SELECT SN
FROM (
SELECT MIN(SN) AS SN FROM DETAILS GROUP BY empname, dept,
CONTACTNO
) AS temp
);
SELECT * FROM DETAILS;
2
Workbench Output:
Conclusion:
This experiment demonstrates the process of removing duplicate rows from a
table by using SQL queries. It is essential for maintaining data integrity in
relational databases.
3
Experiment 2
Displaying Alternate Rows from the Table
Objective:
To retrieve alternate rows from a table.
Theory:
The ROW_NUMBER() function in SQL can be used to assign a unique number to
each row in the result set. By applying the modulo operator, we can select
alternate rows. This operation can be useful when performing tasks such as
pagination or sampling data.
Experiment Procedure:
1. Create a database and table with sample data.
2. Use the ROW_NUMBER() function to assign a row number to each
record.
3. Filter the rows where the row number is odd or even (based on the
desired alternate rows).
4. Display the result.
SQL Query:
SELECT *
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS row_num FROM
employees) temp
WHERE MOD(row_num, 2) = 1;
4
Workbench Output:
Conclusion:
This experiment showcases how to retrieve alternate rows using SQL's
ROW_NUMBER() function combined with the modulo operator, which is useful
for sampling or data analysis tasks.
5
Experiment 3
Deleting Alternate Rows from the Table
Objective:
To delete alternate rows from a table.
Theory:
In SQL, we can use the ROW_NUMBER() function to identify rows based on
their sequence. Once we have assigned row numbers to all records, we can
delete specific rows (such as alternate rows) using a condition on the row
number.
Experiment Procedure:
1. Create a database and table with sample data.
2. Use the ROW_NUMBER() function to assign row numbers to each row.
3. Delete rows with odd or even row numbers using a DELETE query.
4. Verify that the desired rows have been deleted.
SQL Query:
DELETE FROM employees
WHERE id IN (
SELECT id
FROM (SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS row_num FROM
employees) temp
WHERE MOD(row_num, 2) = 1
);
6
Workbench Output:
Conclusion:
This experiment demonstrates how to delete alternate rows from a table,
which can be useful for cleaning data or when performing selective deletions.
7
Experiment 4
Updating Multiple Rows Using a Single Update Statement
Objective:
To update multiple rows in a table simultaneously using a single UPDATE query
with conditional logic.
Theory:
SQL allows us to update multiple rows in a table at once using the UPDATE
statement with a CASE expression. This is helpful when the updates need to be
conditional, such as increasing the salary of employees in different
departments by different percentages.
Experiment Procedure:
1. Create a database and table with sample data.
2. Use an UPDATE statement with a CASE expression to update multiple
rows.
3. Verify the updated rows by using a SELECT query.
SQL Query:
UPDATE employees
SET salary = CASE
WHEN department = 'HR' THEN salary * 1.10
WHEN department = 'Finance' THEN salary * 1.15
END
WHERE department IN ('HR', 'Finance');
8
Workbench Output:
Conclusion:
This experiment highlights the ability to update multiple rows conditionally in a
single query, which is efficient for bulk updates in a table.
9
Experiment 5
Finding the Third Highest Paid and Third Lowest Paid Salary
Objective:
To find the third highest and third lowest salaries in a table.
Theory:
To find specific rankings such as the third highest or lowest values, we can use
LIMIT and OFFSET clauses in combination with ORDER BY. These allow us to
return rows based on their position in a sorted result set.
Experiment Procedure:
1. Create a database and table with salary data.
2. Use the ORDER BY clause to sort the salaries in descending and
ascending order.
3. Apply the LIMIT and OFFSET clauses to retrieve the third highest and
third lowest salary.
SQL Query:
-- Third Highest Paid Salary
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2;
Workbench Output:
Conclusion:
This experiment demonstrates how to retrieve specific ranking salaries from a
table using SQL's LIMIT and OFFSET clauses.
11
Experiment 6
Displaying the 3rd, 4th, and 9th Rows from the Table
Objective:
To retrieve specific rows (e.g., 3rd, 4th, and 9th) from the table.
Theory:
Using the ROW_NUMBER() function, we can assign a unique row number to
each row in a table. We can then filter the result set to retrieve only the
specific rows by referencing their row numbers.
Experiment Procedure:
1. Create a database and table with sample data.
2. Use the ROW_NUMBER() function to assign a number to each row.
3. Retrieve rows with the row numbers 3, 4, and 9.
SQL Query:
SELECT *
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS row_num FROM
employees) temp
WHERE row_num IN (3, 4, 9);
Workbench Output:
12
Conclusion:
This experiment demonstrates how to retrieve specific rows from a table using
the ROW_NUMBER() function.
13
Experiment 7
Displaying Employee Names Starting with J, K, L, or M
Objective:
To retrieve employee names starting with specific letters (J, K, L, or M).
Theory:
The LIKE operator in SQL is used for pattern matching. By using the wildcard
character %, we can match names that start with any given character.
Experiment Procedure:
1. Create a database and table with employee names.
2. Use the LIKE operator to filter names starting with the letters J, K, L, or
M.
3. Display the result.
SQL Query:
SELECT ename
FROM employees
WHERE ename LIKE 'J%' OR ename LIKE 'K%' OR ename LIKE 'L%' OR ename
LIKE 'M%';
14
Workbench Output:
Conclusion:
This experiment demonstrates how to filter records based on pattern matching
using the LIKE operator in SQL.
15
Experiment 8
Show all employees who were hired the first half of the month.
Objective:
To retrieve and display the details of all employees who were hired during the
first 15 days of any month.
Theory:
In SQL, the EXTRACT function can be used to extract parts of a date (such as
day, month, or year) from a DATE field. By using EXTRACT(DAY FROM
hire_date) and filtering for values between 1 and 15, we can fetch
employees hired in the first half of the month.
Experiment Procedure:
Create a table with employee data, including their hire dates. Use the EXTRACT
function to filter records where the hire date falls between the 1st and 15th of
the month.
SQL Query:
SELECT *
FROM employees
WHERE EXTRACT(DAY FROM hire_date) BETWEEN 1 AND 15;
16
Workbench output:
Experiment 9
Display Records in Specific Rows Pattern (3, 2, 1)
Objective:
To display employee records in such a way that 3 records appear in the first
row, 2 records in the second row, and 1 record in the third row.
Theory:
While SQL alone cannot explicitly control the format of the output in rows and
columns as it depends on the environment in which it is executed, you can
control the ordering and limit the number of results displayed. Using ROWNUM
and an ORDER BY clause, we can manipulate how data is returned.
Experiment Procedure:
Retrieve and display the top six records from the employees table in order of
their row number. The display format depends on the tool used to execute the
SQL query (e.g., SQL Developer, MySQL Workbench).
SQL Query:
-- Subquery with ROWNUM for Oracle or equivalent systems
SELECT employee_name, hire_date
FROM (
SELECT employee_name, hire_date, ROWNUM as rnum
FROM employees
ORDER BY hire_date -- Modify the order criteria here
)
Workbench Output:
Experiment 10
SQL Statements for Rollback, Commit, and Savepoints
Objective:
Theory:
Transaction control allows users to group multiple SQL statements into a logical
unit. A SAVEPOINT is a point in the transaction that can be rolled back to
without affecting the entire transaction. COMMIT saves all the changes made,
while ROLLBACK undoes the changes.
Experiment Procedure:
Insert or update records, use SAVEPOINT to mark a specific point, and then
use ROLLBACK to undo changes up to that point or completely.
SQL Query:
-- Begin a transaction
INSERT INTO employees (employee_id, employee_name, hire_date)
VALUES (1001, 'John Doe', SYSDATE);
-- Set a savepoint
SAVEPOINT savepoint1;
-- Another operation
UPDATE employees SET employee_name = 'Jane Doe' WHERE employee_id =
1001;
Workbench Output:
Experiment 11
PL/SQL for SELECT, INSERT, UPDATE, and DELETE Statements
Objective:
Theory:
PL/SQL allows users to perform procedural operations on the data stored in the
database. It includes SQL within the code blocks for querying and manipulating
data.
Experiment Procedure:
Write PL/SQL blocks for each operation (SELECT, INSERT, UPDATE, and
DELETE) to query and manipulate data from the employees table.
PL/SQL Queries:
SELECT:
DELIMITER //
DELIMITER ;
CALL GetEmployeeName(1001);
INSERT:
INSERT INTO employees (id, ename, hire_date)
VALUES (1002, 'Alice Smith', CURDATE());
22
UPDATE:
UPDATE employees
SET ename = 'Updated Name'
WHERE id = 1002;
DELETE:
DELETE FROM employees
WHERE id = 1002;
Workbench Output:
23
Experiment 12
Objective:
To delete an employee record from the database and return 1 if the operation
is successful, else return 0.
Theory:
Experiment Procedure:
Write a PL/SQL block to delete a record based on employee ID. Use the
SQL%ROWCOUNT attribute to check if the record was deleted and return the
appropriate status.
PQL/SQL Query:
CALL GetEmployeeName(1);
INSERT INTO employees (id, ename, hire_date)
VALUES (1002, 'Alice Smith', CURDATE());
Workbench Output:
Experiment 13
Objective:
To display the employee names and their hire dates using cursors in PL/SQL.
Theory:
Experiment Procedure:
Define a cursor for selecting employee names and hire dates, then use a loop
to fetch and display each row.
PQL/SL Query:
DELIMITER //
-- Declare the CONTINUE HANDLER for the cursor to handle the end of the
data
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN emp_cursor;
DELIMITER ;
CALL DisplayEmployeeNamesAndHireDates();
28
Workbench Output:
Output:
e
29
EXPERIMENT 14
Display details of first 5 highly paid employees using cursors.
Objective:
To fetch and display the details of the first 5 employees based on their salaries
(assumed column SN for demonstration).
Theory:
In MySQL, cursors within stored procedures can iterate over sorted query
results, allowing us to display the first n records sequentially.
Experiment Procedure:
MySQL Query:
DELIMITER $$
CREATE PROCEDURE DisplayTop5HighlyPaidEmployees()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE v_sn INT;
DECLARE v_empname VARCHAR(50);
DECLARE v_dept VARCHAR(50);
DECLARE v_contactno BIGINT;
DECLARE v_city VARCHAR(50);
DECLARE emp_cursor CURSOR FOR
SELECT SN, EMPNAME, DEPT, CONTACTNO, CITY
FROM EMPLOYEE
ORDER BY SN DESC
LIMIT 5;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN emp_cursor;
read_loop: LOOP
FETCH emp_cursor INTO v_sn, v_empname, v_dept, v_contactno, v_city;
IF done THEN
31
LEAVE read_loop;
END IF;
SELECT CONCAT(v_sn, ' ', v_empname, ' ', v_dept, ' ', v_contactno, ' ',
v_city) AS EmployeeDetails;
END LOOP;
CLOSE emp_cursor;
END$$
DELIMITER ;
EXECUTION COMMAND:
CALL Top5HighlyPaid();
WORKBENCH OUTPUT:
32
OUTPUTS:
Experiment 15
Write a database trigger that fires if you try to insert, update, or delete after
7’o’clock.
Objective
To create a trigger that prevents any insert, update, or delete operations in the
employees table after 7:00 PM.
Theory
Triggers are procedural code that execute automatically in response to certain
events on a database table. In this experiment, a BEFORE trigger is used to
check the current time and raise an error if the operation is attempted after
7:00 PM. This ensures operational restrictions are enforced.
Experiment Procedure
1. Create the employees table and populate it with sample data.
2. Write BEFORE INSERT, BEFORE UPDATE, and BEFORE DELETE triggers that
check the system time.
3. Use the SIGNAL SQLSTATE statement to raise a custom error message if
the time is past 7:00 PM.
4. Test the triggers by attempting DML operations before and after 7:00
PM.
34
Expected Output:
35
Conclusion:
Triggers effectively enforce time-based restrictions on database operations,
ensuring business rules are maintained.
36
Experiment 1
Write a database trigger that acts like a primary key and does not allow
duplicate values.
Expected Output:
Conclusion
Triggers can be used to enforce data integrity rules that go beyond standard
constraints.
38
Experiment 17
Create a database trigger to perform the action of ON DELETE CASCADE.
Expected Output:
Conclusion
The ON DELETE CASCADE clause in foreign keys ensures data consistency
between parent and child tables.
40
Experiment 18
Write a database trigger that should not allow deletion from the employees
table if the day is Sunday.
Expected Output:
Conclusion:
Triggers can enforce day-based restrictions, ensuring certain operations are
restricted as per business rules.