0% found this document useful (0 votes)
6 views

ilovepdf_merged (1)

The document outlines a series of lab experiments for a database course, including tasks such as drawing E-R diagrams, implementing SQL commands (DDL, DML), using various SQL operators and functions, and creating PL/SQL programs. It covers practical implementations of triggers, cursors, and transaction control language, providing syntax and examples for each concept. The document serves as a comprehensive guide for students to understand and apply database management techniques.

Uploaded by

thakurrishu5592
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)
6 views

ilovepdf_merged (1)

The document outlines a series of lab experiments for a database course, including tasks such as drawing E-R diagrams, implementing SQL commands (DDL, DML), using various SQL operators and functions, and creating PL/SQL programs. It covers practical implementations of triggers, cursors, and transaction control language, providing syntax and examples for each concept. The document serves as a comprehensive guide for students to understand and apply database management techniques.

Uploaded by

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

Student’s Name : Aditya Raj

Semester : 3rd
Admission No: 23SCSE1011178
Section : 20
1.Draw an E-R diagram and convert entities and relationships to a
relation table for a given scenario. (Two assignments shall be carried
out i.e., consider two different scenarios (e.g. bank, College) .

2 L Implementation of DDL commands of SQL with suitable examples


(student and employee). (a) Create table (b) Alter table (c) Drop Table .

3 L Implementation of DML commands of SQL with suitable


examples (student and employee). (a) Insert table (b) Update table (c)
Delete Table (d) Select .

4 L Implementation of different types of operators in SQL.


(a)Arithmetic Operator (b)Logical Operator (c) Comparision Operator
(d)Set Operator .

5 L Implementation of different types of functions with suitable


examples. (a)Number Function (b) Aggregate Function (c) String
Function (d) Conversion Function (e) Date Function .

6 L Perform the following: a. Creating Tables (With and Without


Constraints (Key/Domain) b. Creating Tables (With Referential
Integrity Constraints) .

7 L Execute Queries using the Select command with Where, Having,


Group by and order by clauses.

8 L Implementation of different types of constraints: Primary key,


Foreign key, Unique key constraint, Null, Not Null.
9 L Implementation of different types of joins in SQL.

10 L Implementation of SQL Sub-Query and Views.

11 L Execute the SQL Queries (using ANY, IN,NOTIN UNION


UNION ALL.) .

12 L To implement PL/SQL program using control structures,


procedures and functions.

13 L Implementation of Triggers in SQL (Creation of insert trigger,


delete trigger, update trigger).

14 L Implementation of Cursors in SQL.

15 L Implementation of Transaction Control Language and Data


Control Language
Lab Experiment 1

AIM:-Draw an E-R diagram and convert entities and relationships to a relation table for
a given scenario. (Two assignments shall be carried out i.e., consider two different
scenarios (e.g. bank, College) .

Banking System
Collage System:-
Experiment 11

5. Execute the SQL Queries (using ANY, IN,NOTIN UNION UNION ALL.)
Solution : IN, NOT IN operators in SQL are used with SELECT, UPDATE and DELETE
statements/queries to select, update and delete only particular records in a table those meet the condition
given in WHERE clause and conditions given in IN, NOT IN operators. I.e. it filters records from a table
as per the condition.

Syntax for SQL IN & NOT IN operators are given below.

The UNION command combines the result set of two or more SELECT statements (only distinct values)
The following SQL statement returns the cities (only distinct values) from both the "Customers" and the
"Suppliers" table: Example
SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City;
The UNION ALL command combines the result set of two or more SELECT statements (allows duplicate
values).
Example
SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers ORDER BY City;

The IN operator is used when you want to retrieve a column that has entries in the table or referencing table.
Syntax
expression IN (value1, value2, value_n);
query
1) select * from employee where ename In('ramesh','mahesh','suresh');
2) select ename from employee where eid In(select eid from
project where employee.eid=project.eid);
3) select ename,salary from employee where eid In(select eid from
project where employee.eid=project.eid);

2) NOT IN

The NOT IN operator is used when you want to retrieve a column that has no entries in the table or
referencing table. select * from employee where ename Not In('ramesh','mahesh','suresh');

3) ANY

The ANY operator returns true if any of the subquery values meet the condition.
Syntax
SELECT column_name(s) FROM table_name WHERE column_name operator ANY (SELECT column_name
FROM
table_name WHERE condition);
select * from employee where eid=ANY(select eid from project where employee.eid=project.eid);
The ALL operator returns true if all of the subquery values meet the
condition. ALL Syntax
SELECT column_name(s) FROM table_name WHERE column_name operator ALL (SELECT column_name
FROM
table_name WHERE condition);
UNION
The UNION operator is used to combine the result-set of two or more
SELECT statements. Each SELECT statement within UNION must have the
same number of columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the same order

UNION Syntax
SELECT column_name(s) FROM table1 UNION SELECT column_name(s)
FROM table2; Example
Create table emp1(eid int,ename varchar(20),address
varchar(20),salary int(20)); Create table emp2(eid int,ename
varchar(20),address varchar(20),salary int(20))
Experiment 12

6. To implement PL/SQL program using control structures, procedures and functions.


Solution:
Structure:

1. Control Structures: Flow control, such as IF, LOOP, WHILE, etc.


2. Procedures: Subprograms that perform actions and can optionally take input/output parameters.
3. Functions: Subprograms that return a value.

Example: PL/SQL Program Using Control Structures, Procedures, and Functions

Let’s create a PL/SQL program that manages employee data, with the following features:

 A procedure to add a new employee.


 A function to calculate an employee's annual salary.
 Control structures to check if the employee already exists and to manage program flow

The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or more
specific tasks. It is just like procedures in other programming languages.
Syntax for creating procedures
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
<
procedure_body >
END
procedure_name;

Step 1: Create a Sample Table


First, we’ll create an employees table to store
employee data. CREATE TABLE employees (
employee_id NUMBER
PRIMARY KEY, employee_name
VARCHAR2(100), salary
NUMBER(10, 2),
department VARCHAR2(50)
);
Step 2: PL/SQL Procedure to Add an Employee
A procedure is used to perform operations such as inserting data into
a table. CREATE OR REPLACE PROCEDURE
add_employee(p_employee_id IN NUNUMBER,)
p_employee_name IN
VARCHAR2, p_salary IN
NUMBER, p_department IN
VARCHAR2
) AS
-- Declare variables
v_exists NUMBER;
BEGIN
-- Check if the employee already
exists SELECT COUNT(*)
INTO v_exists
FROM
employees
WHERE employee_id = p_employee_id;

-- If employee exists, raise an


exception IF v_exists > 0 THEN
DBMS_OUTPUT.PUT_LINE('Employee with ID ' || p_employee_id || '
already exists.'); ELSE
-- Insert the new employee
INSERT INTO employees (employee_id, employee_name, salary,
department) VALUES (p_employee_id, p_employee_name, p_salary,
p_department); DBMS_OUTPUT.PUT_LINE('Employee added: ' ||
p_employee_name);
END IF;
EXCEPTI
ON
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' ||
SQLERRM);
END;

Step 3: PL/SQL Function to Calculate Annual Salary


A function returns a value, such as calculating an employee's annual salary based on their monthly salary.

CREATE OR REPLACE FUNCTION


calculate_annual_salary( p_employee_id IN NUMBER
) RETURN NUMBER IS
v_salary NUMBER;
v_annual_salary
NUMBER;
BEGIN
Fetch the employee's salary
SELECT salary INTO v_salary FROM employees WHERE employee_id = p_employee_id;

Calculate the annual salary (assuming 12


months) v_annual_salary := v_salary * 12;

RETURN
v_annual_salary;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee
not found'); RETURN 0;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' ||
SQLERRM); RETURN 0;
END;

Step 4: PL/SQL Block with Control Structure

Now, let’s create an anonymous PL/SQL block that uses both the procedure and the function, with
control structures to manage the flow.

BEGIN
Declare
variables
DECLARE
v_emp_id NUMBER := 101;
v_emp_name VARCHAR2(100) := 'John Doe';v_salary NUMBER := 5000; v_department VARCHAR2(50)
:= 'Sales'; v_annual_salary NUMBER;
BEGIN
Add a new employee
add_employee(v_emp_id, v_emp_name, v_salary, v_department);

Calculate the annual salary using the function


v_annual_salary :=
calculate_annual_salary(v_emp_id);

Control structure: If salary is calculated,


display it IF v_annual_salary > 0 THEN
DBMS_OUTPUT.PUT_LINE('Annual salary of ' || v_emp_name || ' is: ' ||
v_annual_salary); ELSE
DBMS_OUTPUT.PUT_LINE('Failed to calculate annual
salary.'); END IF;
EN
D;
END;
Breakdown of Components:
Procedure (add_employee):

Adds a new employee to the employees table.

Uses control structure (IF-ELSE) to check if the employee already exists and
prevent duplication. Handles exceptions with the EXCEPTION block.
Function (calculate_annual_salary):

Returns the annual salary of an employee.


Uses an exception handler for cases where the employee does
not exist. Control Structures:

IF-ELSE control structure is used to check conditions (e.g., if the employee exists or if the
salary calculation was successful).
Error handling is done using EXCEPTION blocks to catch and handle any runtime
errors. Execution and Output:
Add a new employee: The add_employee procedure will insert a new row into the employees table.
Calculate the annual salary: The calculate_annual_salary function will return the calculated
salary and display it. Example Output:

Employee added: John Doe


Annual salary of John Doe is: 60000
Experiment 13

7. Implementing of Triggers in SQL (Creation of insert trigger, delete trigger, update trigger).
Solution: Triggers are stored programs, which are automatically executed or fired when some event occurs.
Syntax for creating trigger:
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

1. Creating an INSERT Trigger


Example: Automatically log details into an audit table when a new row is inserted into the employees table.

Create a table to store audit


logs CREATE TABLE
employee_audit (
audit_id INT IDENTITY(1,1),
employee_id INT,
employee_name
VARCHAR(100),
operation_type
VARCHAR(10),
operation_time DATETIME
);

-- Create an INSERT trigger


CREATE TRIGGER
trg_after_employee_insert ON employees
AFTER
INSERT AS
BEGIN
-- Insert into audit log after an employee is inserted
INSERT INTO employee_audit (employee_id, employee_name, operation_type,
operation_time) SELECT employee_id, employee_name, 'INSERT', GETDATE()
FROM
inserted; END;
In this case:

inserted is a special table containing the new rows that have been inserted into employees.
2. Creating a DELETE Trigger
Example: Automatically log details when a row is deleted from the employees table.

Create a DELETE trigger


CREATE TRIGGER
trg_after_employee_delete ON employees
AFTER
DELETE AS
BEGIN
-- Insert into audit log after an employee is deleted
INSERT INTO employee_audit (employee_id, employee_name, operation_type,
operation_time) SELECT employee_id, employee_name, 'DELETE', GETDATE()
FROM
deleted; END;
In this case:

deleted is a special table that contains the rows that were deleted from the employees table.
3. Creating an UPDATE Trigger
Example: Automatically log details when a row is updated in the employees table.

-- Create an UPDATE trigger


CREATE TRIGGER
trg_after_employee_update ON
employees
AFTER
UPDATE AS
BEGIN
-- Insert into audit log after an employee is updated
INSERT INTO employee_audit (employee_id, employee_name, operation_type,
operation_time) SELECT employee_id, employee_name, 'UPDATE', GETDATE()
FROM
inserted; END;
CREATE TRIGGER
trg_employee_audit ON
employees
AFTER INSERT, UPDATE,
DELETE AS
BEGIN
-- For INSERT
INSERT INTO employee_audit (employee_id, employee_name, operation_type,
operation_time) SELECT employee_id, employee_name, 'INSERT', GETDATE()
FROM inserted;

-- For DELETE
INSERT INTO employee_audit (employee_id, employee_name, operation_type,
operation_time) SELECT employee_id, employee_name, 'DELETE', GETDATE()
FROM deleted;

-- For UPDATE
IF EXISTS (SELECT 1 FROM inserted) AND EXISTS (SELECT 1
FROM deleted) BEGIN
INSERT INTO employee_audit (employee_id, employee_name, operation_type,
operation_time) SELECT employee_id, employee_name, 'UPDATE', GETDATE()
FROM
inserted; END;
END;
Experiment 14

8. Implementing and usage of Cursors in SQL.


Solution: Cursors In MySQL, a cursor allows row-by-row processing of the result sets. A cursor is
used for the result set and returned from a query. By using a cursor, you can iterate, or by step through
the results of a query and perform certain operations on each row. The cursor allows you to iterate
through the result set and then perform the additional processing only on the rows that require it. In a
cursor contains the data in a loop. Cursors may be different from SQL commands that operate on all
the rows in the returned by a query at one time.
There are some steps we have to follow, given below :
 Declare a cursor
 Open a cursor statement
 Fetch the cursor
 Close the cursor

1. Declare a Cursor DECLARE cursor_name CURSOR FOR SELECT column1, column2, ... FROM table_name WHERE
condition;
2. Open the Cursor OPEN cursor_name;
3. Fetch Rows from the Cursor FETCH NEXT FROM cursor_name INTO @variable1, @variable2,
4. Loop through all rows WHILE @@FETCH_STATUS = 0 BEGIN Process each row
Example: PRINT the fetched values PRINT @variable1; PRINT @variable2; Fetch the next row FETCH
NEXT FROM cursor_name INTO @variable1, @variable2, ...; END;
5. Close the Cursor CLOSE cursor_name;
6. Deallocate the Cursor DEALLOCATE cursor_name;

Declare Cursor to select employee data DECLARE emp_cursor CURSOR FOR SELECT employee_id,
employee_name FROM employees WHERE department = 'Sales';

Variables to hold fetched data DECLARE @emp_id INT; DECLARE @emp_name VARCHAR(100);
2. Open the Cursor OPEN emp_cursor;
3. Fetch the first row from the cursor FETCH NEXT FROM emp_cursor INTO @emp_id, @emp_name;
4. Process the fetched rows WHILE @@FETCH_STATUS = 0
BEGIN -- Example: Print employee details PRINT 'Employee ID: ' + CAST(@emp_id AS VARCHAR); PRINT
'Employee Name: ' + @emp_name;
Fetch the next row FETCH NEXT FROM emp_cursor INTO @emp_id, @emp_name; END;
5. Close the Cursor CLOSE emp_cursor;
6. Deallocate the Cursor DEALLOCATE emp_cursor;
Experiment 15

9. Implementation of TRANSATIONAL CONTROL LANGUAGE and DATA CONTROL LANGUAGE.


A transaction is a logical unit of work. All changes made to the database can be referred to as a transaction.
Transaction changes can be made permanent to the database only if they are committed a transaction begins
with an executable SQL statement & ends explicitly with either rollback or commit statement.

1. COMMIT: This command is used to end a transaction only with the help of the commit command
transaction changes can be made permanent to the database.

Syntax: SQL> COMMIT;


Example: SQL> COMMIT;

2. SAVE POINT: Save points are like marks to divide a very lengthy transaction to smaller once. They are
used to identify a point in a transaction to which we can latter role back. Thus, save point is used in conjunction
with role back.

Syntax: SQL> SAVE POINT ID;


Example: SQL> SAVE POINT xyz;

3. ROLLBACK: A role back command is used to undo the current transactions. We can role back the entire
transaction so that all changes made by SQL statements are undo (or) role back transaction to save a point so
that sql after statement after the save point rollback.

Syntax: ROLLBACK (current transaction can be role back) ROLLBACK to save point ID;
Example: SQL> ROLLBACK;
SQL> ROLLBACK TO SAVE POINT xyz;
LAB PRACTICE ASSIGNMENT:
1. Write a query to implement the save point.
2. Write a query to implement the rollback.
3. Write a query to implement the commit.

DCL provides uses with privilege commands the owner of database objects (tables), has the soul authority
ollas them. The owner (data base administrators) can allow other data base uses to access the objects as
per their requirement.

1. GRANT: The GRANT command allows granting various privileges to other users and allowing them to perform
operations with in their privileges
2. For Example, if a uses is granted as ‘SELECT’ privilege then he/she can only view data but cannot perform any other
DML operations on the data base object GRANTED privileges can also be withdrawn by the DBA at any time
3. Syntax: SQL>GRANT PRIVILEGES on object_name To user_name;
4. Example: SQL>GRANT SELECT, UPDATE on empTohemanth;
5. REVOKE: To with draw the privileges that has been GRANTED to a uses, we use the REVOKE command
6. Syntax: SQL>REVOKE PRIVILEGES ON object-name FROM user_name;
7. Example: SQL>REVOKE SELECT, UPDATE ONemp FROM ravi;
Student’s Name : Aditya Raj
Semester : 3rd
Admission No: 23SCSE1011178
Section : 20
1.Draw an E-R diagram and convert entities and relationships to a
relation table for a given scenario. (Two assignments shall be carried
out i.e., consider two different scenarios (e.g. bank, College) .

2 L Implementation of DDL commands of SQL with suitable examples


(student and employee). (a) Create table (b) Alter table (c) Drop Table .

3 L Implementation of DML commands of SQL with suitable


examples (student and employee). (a) Insert table (b) Update table (c)
Delete Table (d) Select .

4 L Implementation of different types of operators in SQL.


(a)Arithmetic Operator (b)Logical Operator (c) Comparision Operator
(d)Set Operator .

5 L Implementation of different types of functions with suitable


examples. (a)Number Function (b) Aggregate Function (c) String
Function (d) Conversion Function (e) Date Function .

6 L Perform the following: a. Creating Tables (With and Without


Constraints (Key/Domain) b. Creating Tables (With Referential
Integrity Constraints) .

7 L Execute Queries using the Select command with Where, Having,


Group by and order by clauses.

8 L Implementation of different types of constraints: Primary key,


Foreign key, Unique key constraint, Null, Not Null.
9 L Implementation of different types of joins in SQL.

10 L Implementation of SQL Sub-Query and Views.

11 L Execute the SQL Queries (using ANY, IN,NOTIN UNION


UNION ALL.) .

12 L To implement PL/SQL program using control structures,


procedures and functions.

13 L Implementation of Triggers in SQL (Creation of insert trigger,


delete trigger, update trigger).

14 L Implementation of Cursors in SQL.

15 L Implementation of Transaction Control Language and Data


Control Language
Lab Experiment 1

AIM:-Draw an E-R diagram and convert entities and relationships to a relation table for
a given scenario. (Two assignments shall be carried out i.e., consider two different
scenarios (e.g. bank, College) .

Banking System
Collage System:-

You might also like