Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

manual_mridul

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

VIT BHOPAL UNIVERSITY

SCHOOL OF COMPUTING SCIENCE ENGINEERING

LAB MANUAL

COURSE NAME : DATABASE MANAGEMENT SYSTEM (DBMS)


COURSE CODE : CSE3001
NAME OF FACULTY MEMBER : DR. RAVI VERMA
SESSION : INTERIM SEMESTER 2024-25

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;

-- Third Lowest Paid Salary


SELECT DISTINCT salary
FROM employees
ORDER BY salary ASC
LIMIT 1 OFFSET 2;
10

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:

Conclusion: Successfully retrieved employee data based on hire dates within


the first 15 days.
17

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
)

WHERE rnum <= 6;


18

Workbench Output:

Conclusion: Demonstrated customized result display using the ROW_NUMBER()


function for specific row formatting.
19

Experiment 10
SQL Statements for Rollback, Commit, and Savepoints

Objective:

To demonstrate how to use transaction control statements such as


SAVEPOINT, ROLLBACK, and COMMIT in SQL to manage data integrity.

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;

-- Commit the transaction


COMMIT;
20

-- Rollback to the savepoint or rollback the entire transaction


ROLLBACK TO savepoint1;
ROLLBACK;

Workbench Output:

Conclusion: Effectively managed transactions with rollback, commit, and


savepoint commands.
21

Experiment 11
PL/SQL for SELECT, INSERT, UPDATE, and DELETE Statements

Objective:

To perform basic SELECT, INSERT, UPDATE, and DELETE operations using


PL/SQL.

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 //

CREATE PROCEDURE GetEmployeeName(IN employeeID INT)


BEGIN
DECLARE v_employee_name VARCHAR(100);

SELECT ename INTO v_employee_name


FROM employees
WHERE id = employeeID;

SELECT v_employee_name AS EmployeeName;


END //

DELIMITER ;
CALL GetEmployeeName(1001);

 INSERT:
INSERT INTO employees (id, ename, hire_date)
VALUES (1002, 'Alice Smith', CURDATE());
22

SELECT 'Record inserted successfully' AS Message;

 UPDATE:
UPDATE employees
SET ename = 'Updated Name'
WHERE id = 1002;

SELECT 'Record updated successfully' AS Message;

 DELETE:
DELETE FROM employees
WHERE id = 1002;

SELECT 'Record deleted successfully' AS Message;

Workbench Output:
23

Conclusion: Performed CRUD operations using PL/SQL blocks to manipulate


employee data.
24

Experiment 12

PL/SQL Block to Delete a Record and Return Status

Objective:

To delete an employee record from the database and return 1 if the operation
is successful, else return 0.

Theory:

In PL/SQL, after executing a DELETE statement, we can check the number of


affected rows using the SQL%ROWCOUNT implicit cursor attribute. This value can
be used to return the status of the operation.

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());

SELECT 'Record inserted successfully' AS Message;


UPDATE employees
SET ename = 'Updated Name'
WHERE id = 1002;

SELECT 'Record updated successfully' AS Message;


25

DELETE FROM employees


WHERE id = 1002;

SELECT 'Record deleted successfully' AS Message;

Workbench Output:

Conclusion: Implemented record deletion with conditional status return based


on the operation’s success.
26

Experiment 13

Display Name and Hire Date of all Employees Using Cursors

Objective:

To display the employee names and their hire dates using cursors in PL/SQL.

Theory:

Cursors allow row-by-row processing of result sets in PL/SQL. We can fetch


multiple rows of data from a query into variables using a cursor and loop
through the results.

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 //

CREATE PROCEDURE DisplayEmployeeNamesAndHireDates()


BEGIN
-- Declare the cursor variables
DECLARE done INT DEFAULT 0;
DECLARE v_employee_name VARCHAR(100);
DECLARE v_hire_date DATE;

-- Declare the cursor for employee names and hire dates


DECLARE emp_cursor CURSOR FOR
SELECT ename, hire_date FROM employees;

-- Declare the CONTINUE HANDLER for the cursor to handle the end of the
data
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

-- Open the cursor


27

OPEN emp_cursor;

-- Loop through the cursor


read_loop: LOOP
FETCH emp_cursor INTO v_employee_name, v_hire_date;

-- Exit the loop when no more records are found


IF done THEN
LEAVE read_loop;
END IF;

-- Output the employee name and hire date


SELECT CONCAT('Name: ', v_employee_name, ', Hire Date: ', v_hire_date)
AS EmployeeInfo;
END LOOP;

-- Close the cursor


CLOSE emp_cursor;
END //

DELIMITER ;
CALL DisplayEmployeeNamesAndHireDates();
28

Workbench Output:

Output:

e
29

Conclusion: Successfully fetched and displayed employee details using cursors


in a stored procedure.
30

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:

1. Sort the records by salary (using SN for this example).


2. Create a cursor to iterate through the first 5 rows.
3. Use a loop to fetch and display each record.

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:

Conclusion: This experiment demonstrates the use of cursors to fetch and


display details of the top-paid employees. It is crucial for implementing ranking
and filtering operations in database queries.
33

Experiment 15
Write a database trigger that fires if you try to insert, update, or delete after
7’o’clock.

Title of the Experiment


Restrict DML Operations After 7:00 PM Using a Trigger

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.

Title of the Experiment


Simulating Primary Key Behavior Using a Trigger
Objective
To create a trigger that prevents duplicate values for the ename column in the
employees table, simulating the behavior of a primary key.
Theory
A trigger can check for duplicates in a column before an insert operation. If a
duplicate value is detected, the trigger raises an error, preventing the
operation. This provides an additional layer of data integrity.
Experiment Procedure
1. Create the employees table with a unique column ename.
2. Write a BEFORE INSERT trigger to check for existing values in the ename
column.
3. Use the EXISTS keyword in the trigger to identify duplicates.
4. Test the trigger by inserting records with unique and duplicate ename
values.
37

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.

Title of the Experiment


Implementing ON DELETE CASCADE Using a Trigger
Objective
To demonstrate how foreign keys with ON DELETE CASCADE automatically
delete related records in child tables when a parent record is deleted.
Theory
The ON DELETE CASCADE clause in a foreign key constraint ensures referential
integrity by automatically deleting records in a child table when the
corresponding parent record is deleted. No explicit trigger is needed for this
functionality as it is handled by MySQL’s referential integrity system.
Experiment Procedure
1. Create the employees table (parent table) and projects table (child
table).
2. Define a foreign key in the projects table with the ON DELETE CASCADE
option.
3. Insert records into both tables, ensuring relationships exist.
4. Delete a record from the employees table and observe the cascading
effect on the projects table.
39

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.

Title of the Experiment


Restrict Deletion on Sundays Using a Trigger
Objective
To create a trigger that prevents deletion operations on the employees table if
the current day is Sunday.
Theory
Triggers can enforce conditional rules based on system date and time. A
BEFORE DELETE trigger can check the current day using the DAYNAME()
function and raise an error if the condition is met.
Experiment Procedure
1. Create the employees table and populate it with sample data.
2. Write a BEFORE DELETE trigger to check the current day using the
DAYNAME() function.
3. Use the SIGNAL SQLSTATE statement to raise an error if the day is
Sunday.
4. Test the trigger by attempting to delete records on a Sunday and other
days of the week.
41

Expected Output:

Conclusion:
Triggers can enforce day-based restrictions, ensuring certain operations are
restricted as per business rules.

You might also like