Devansh Dbms File
Devansh Dbms File
Greater Noida
(An Autonomus Institute)
LAB FILE
Session: 2025-26
2401330120023
Program 1
Understand and implement the different ER diagram notation with their relationship and Cardinalities.
ER Diagram
An Entity Relationship (ER) Diagram is a graphical representation used in Database Management Systems (DBMS)
to model the structure of a database. It shows entities, attributes, relationships, and cardinality constraints.
Attribute
Describes properties of an entity. Representation: Oval (Ellipse).
Types of Attributes:
Key Attribute
Key attributes are specialized attributes that uniquely identify each entity within an entity set. It can be represented
by underlining the attribute name in Entity-Relationship (ER) diagrams.
Multivalued Attribute
It can be an attribute that can hold multiple values for a single entity instance, unlike singlevalued attributes.
Represented by a double ellipse in Entity-Relationship (ER) diagrams
Derived Attribute
A derived attribute is a data field in a database or model that is calculated or derived from other existing attributes,
rather than being stored directly.
It can be represented in entity-relationship (ER) diagrams with a dotted ellipse.
Composite Attribute
It is an attribute that can be divided into smaller, simpler, and meaningful sub-attributes, rather than being atomic.
2401330120023
Relationship
Shows association between two entities. Representation: Diamond shape.
Weak Entity
Cardinalities in ER Diagram
Cardinality defines how many instances of one entity relate to another entity. One-to-One (1:1)
One entity relates to only one entity.
One-to-Many (1:N)
One entity relates to many entities.
Many-to-One (N:1)
Many entities relate to one entity.
Many-to-Many (M:N)
Many entities relate to many entities.
2401330120023
For Example:
2401330120023
Program 2
Creating ER Diagram for company Database. Company database have entities like employee,
departments, projects and dependents also implement the relationship and cardinalities between the
entities with their relevant attribute.
2401330120023
The Department entity stores information about different departments in the organization.
Its attributes include Dept_ID, Dept_Name, and Contact, which uniquely identify and describe each
department.
The Project entity represents projects handled by the organization.
2401330120023
Program 3
Implement DDL, DML, DCL & TCL commands
Code:
CREATE TABLE student (
id INT,
name VARCHAR(50),
age INT
);
DESC student;
Output:
ALTER : The ALTER command is used to modify the structure of an existing table.
Code:
ALTER TABLE student ADD city VARCHAR(50); DESC student;
Output:
2401330120023
TRUNCATE : The TRUNCATE command is used to remove all records from a table but keep the table
structure.
Code:
TRUNCATE TABLE student; SELECT * FROM student;
Output:
Code:
DROP TABLE student;
Output:
2401330120023
2. DML (Data Manipulation Language)
DML (Data Manipulation Language) is used to manage and manipulate the data stored in database tables.
These commands allow users to insert, update, delete, and retrieve data from the database. DML commands
work on the data inside the tables rather than changing the structure of the database.
Common DML Commands
INSERT: The INSERT command is used to add new records into a table.
Code:
CREATE TABLE student (
id INT,
name VARCHAR(50),
age INT,
city VARCHAR(50)
);
INSERT INTO student VALUES (1, 'Varun Shukla', 20, 'Delhi');
INSERT INTO student VALUES (2, 'Vikas Rathore', 19, 'Mumbai');
INSERT INTO student VALUES (3, 'Shivam Nishad', 21, 'Lucknow');
SELECT * FROM student;
Output:
SELECT: The SELECT command is used to retrieve or display data from a table.
Code:
SELECT name, age FROM student WHERE age > 19;
2401330120023
Output:
Code:
UPDATE student SET age = 22 WHERE name = 'Vikas Rathore';
SELECT * FROM student;
Output:
Code:
DELETE FROM student WHERE id = 3;
SELECT * FROM student;
Output:
2401330120023
3. DCL (Data Control Language)
DCL (Data Control Language) is used to control access to the database. These commands allow
administrators to grant or remove permissions for users to perform operations on database objects such as
tables and views.
Common DCL Commands
GRANT: The GRANT command is used to give specific privileges to users on database objects.
Code:
CREATE USER 'varun'@'localhost' IDENTIFIED BY 'varun@123';
CREATE USER 'vikas'@'localhost' IDENTIFIED BY 'vikas@123';
GRANT SELECT, INSERT ON [Link] TO 'varun'@'localhost';
GRANT SELECT ON [Link] TO 'vikas'@'localhost';
REVOKE INSERT ON [Link] FROM 'varun'@'localhost';
Output:
REVOKE: The REVOKE command is used to remove privileges previously granted to a user.
Code:
CREATE USER 'student1'@'localhost' IDENTIFIED BY '1234';
GRANT ALL PRIVILEGES ON college.* TO 'student1'@'localhost';
REVOKE ALL PRIVILEGES ON college.* FROM 'student1'@'localhost';
Output:
2401330120023
4. TCL (Transaction Control Language)
TCL (Transaction Control Language) is used to manage transactions in a database. These commands help
maintain data consistency and integrity by controlling changes made by DML statements.
Common TCL Commands
COMMIT: The COMMIT command is used to permanently save all the changes made during the current
transaction.
Code:
SET autocommit = 0; SELECT * FROM student;
UPDATE student SET city = 'Agra' WHERE id = 1; COMMIT;
DELETE FROM student WHERE id = 2; ROLLBACK;
SELECT * FROM student;
Output:
ROLLBACK: The ROLLBACK command is used to undo changes made during the current transaction.
Code:
ROLLBACK;
Output:
2401330120023
Program 4
Implementation of I/O Constraint: Primary Key, composite primary key, Foreign Key with on delete
set null and on delete set null constraint, Unique Key
1. Primary Key
A Primary Key uniquely identifies each record in a table. It cannot contain NULL values and must be unique
for every row.
Code:
CREATE TABLE student (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT
);
Output:
Code:
CREATE TABLE enrollment ( student_id INT,
course_id INT,
enroll_date DATE,
PRIMARY KEY (student_id, course_id)
);
Output:
2401330120023
3. Foreign Key with ON DELETE SET NULL
A Foreign Key links two tables. ON DELETE SET NULL means that when the referenced row in the parent
table is deleted, the foreign key value in the child table is automatically set to NULL.
Code:
CREATE TABLE dept (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(50)
);
CREATE TABLE student2 (
Id INT PRIMARY KEY,
Name VARCHAR(50),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES dept(dept_id) ON DELETE SET NULL
);
INSERT INTO dept VALUES (10, 'Science'), (20, 'Commerce'), (30, 'Arts');
INSERT INTO student2 VALUES (1, 'Varun Shukla', 10), (2, 'Vikas Rathore', 20);
Output:
Code:
DELETE FROM dept WHERE dept_id = 10;
SELECT * FROM student2;
Output:
6. Unique Key
A Unique Key ensures that all values in a column are different. Unlike Primary Key, a Unique Key column
can contain NULL values.
2401330120023
Code:
CREATE TABLE student4 ( id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100) UNIQUE
);
DESC student4;
INSERT INTO student4 VALUES (1, 'Varun Shukla', 'varun@[Link]');
INSERT INTO student4 VALUES (2, 'Vikas Rathore', 'vikas@[Link]');
SELECT * FROM student4;
Output:
2401330120023
Program 5
Code:
CREATE TABLE student_notnull ( id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
city VARCHAR(50) NOT NULL
);
DESC student_notnull;
INSERT INTO student_notnull VALUES (1, 'Varun Shukla', 'Delhi');
SELECT * FROM student_notnull;
Output:
2. NULL Constraint
The NULL constraint allows a column to store NULL values. This is the default behavior in SQL if no
constraint is specified.
Code:
CREATE TABLE student_null ( id INT PRIMARY KEY,
name VARCHAR(50) NULL,
city VARCHAR(50) NULL
);
DESC student_null;
INSERT INTO student_null(id, name) VALUES (1, 'Varun Shukla');
INSERT INTO student_null VALUES (2, NULL, NULL);
SELECT * FROM student_null;
2401330120023
Output:
3. DEFAULT Constraint
The DEFAULT constraint provides a default value for a column when no value is specified during an
INSERT operation.
Code:
CREATE TABLE student_default ( id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
city VARCHAR(50) DEFAULT 'Delhi',
status VARCHAR(20) DEFAULT 'Active'
);
DESC student_default;
INSERT INTO student_default(id, name)VALUES (1, 'Varun Shukla');
INSERT INTO student_default VALUES (2, 'Vikas Rathore', 'Mumbai', 'Active');
INSERT INTO student_default(id, name, city) VALUES (3, 'Shivam Nishad', 'Lucknow');
SELECT * FROM student_default;
2401330120023
Output:
4. CHECK Constraint
constraint limits the values that can be inserted into a column based on a condition. If the condition is false,
the insertion or update is rejected.
Code:
CREATE TABLE student_check ( id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT, fee INT,
CHECK (age >= 18), CHECK (fee > 0)
);
DESC student_check;
INSERT INTO student_check VALUES (1, 'Varun Shukla', 20, 5000);
INSERT INTO student_check VALUES (2, 'Vikas Rathore', 19, 4500);
SELECT * FROM student_check;
2401330120023
Output:
2401330120023
Program 6
Practicing Queries using Like, Between, Aliases, distinct Operator & Predicate. And Implement
Aggregate Functions.
Code:
CREATE TABLE student ( id INT PRIMARY KEY, name VARCHAR(50),
age INT,
city VARCHAR(50),
fee INT,
dept VARCHAR(30)
);
INSERT INTO student VALUES
(1, 'Varun Shukla', 20, 'Delhi', 5000, 'Science'),
(2, 'Vikas Rathore', 19, 'Mumbai', 4500, 'Commerce'),
(3, 'Shivam Nishad', 21, 'Lucknow', 6000, 'Science'),
(4, 'Rohit Verma', 22, 'Delhi', 7000, 'Arts'),
(5, 'Rahul Gupta', 20, 'Kanpur', 4000, 'Commerce'),
(6, 'Neha Sharma', 23, 'Mumbai', 8000, 'Science'); SELECT * FROM student;
Output:
1. LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. Wildcard
characters: % (any sequence of characters), _ (single character).
Code:
SELECT * FROM student WHERE name LIKE 'V%';
SELECT * FROM student WHERE name LIKE '%Nishad';
SELECT * FROM student WHERE name LIKE '
2401330120023
Output:
2. BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The range is inclusive on both ends.
Code:
SELECT * FROM student WHERE age BETWEEN 19 AND 21;
Output:
3. Aliases (AS)
Aliases are used to give a table or a column a temporary name. They make column names more readable in
the output.
Code:
SELECT name AS Student_Name, age AS Student_Age, fee AS Fees FROM student;
Output:
2401330120023
4. PREDICATE Operator
A Predicate in SQL is a condition used in a WHERE clause to filter records from a table.
Code:
SELECT * FROM student WHERE city IN ('Delhi', 'Mumbai');
Output:
5. DISTINCT Operator
The DISTINCT keyword is used to return only unique (different) values. It removes duplicate values from
the result.
Code:
SELECT DISTINCT city FROM student;
Output:
6. Aggregate Functions
Aggregate functions perform a calculation on a set of values and return a single value. Common functions:
COUNT(), SUM(), AVG(), MAX(), MIN().
Code:
AVG(), MAX(), MIN().
SELECT COUNT(*) AS Total, SUM(fee) AS Sum_Fee,
AVG(fee) AS Avg_Fee, MAX(fee) AS Max_Fee, MIN(fee) AS Min_Fee FROM student;
2401330120023
Output:
2401330120023
Program 7
Implementation of Queries using Where, Group by, Having and Order by Clause.
1. WHERE Clause
The WHERE clause is used to filter records. It extracts only those records that fulfil a specified condition.
Code:
SELECT name, age, city FROM student WHERE age > 20;
Output:
2. GROUP BY Clause
The GROUP BY clause groups rows that have the same values in specified columns into summary rows. It
is often used with aggregate functions.
Code:
SELECT dept, COUNT(*) AS Total FROM student
GROUP BY dept;
Output:
3. HAVING Clause
The HAVING clause is used to filter groups based on aggregate function results. It is like WHERE but for
groups. HAVING is always used after GROUP BY.
Code:
SELECT dept, COUNT(*) AS Total FROM student
GROUP BY dept HAVING COUNT(*) > 1;
2401330120023
Output:
4. ORDER BY Clause
The ORDER BY clause is used to sort the result set in ascending (ASC) or descending (DESC) order. By
default, it sorts in ascending order.
Code:
SELECT name, age FROM student ORDER BY age ASC;
SELECT name, fee FROM student ORDER BY fee DESC;
Output:
2401330120023
Program 8
Create a table EMPLOYEE with following schema: (Emp_no, E_name, E_address, E_ph_no, Dept_no,
Dept_name, Job_id, Designation, Salary).
Table Creation :
Code:
CREATE TABLE EMPLOYEE ( Emp_no INT PRIMARY KEY, E_name VARCHAR(50),
E_address VARCHAR(100),
E_ph_no VARCHAR(15), Dept_no INT,
Dept_name VARCHAR(30),
Job_id VARCHAR(20),
Designation VARCHAR(30),
Salary DECIMAL(10,2),
Hiredate DATE
);
INSERT INTO EMPLOYEE VALUES
(101,'Varun Shukla', 'Delhi', '9876543210',10,'IT','J001','MANAGER', 25000,'1982-06-15'),
(102,'Vikas Rathore','Mumbai', '9988776655',20,'HR','J002','CLERK', 15000,'1981-09-08'),
(103,'Shivam Nishad','Lucknow','9111223344',10,'IT','J001','ANALYST', 18000,'1982-11-10'),
(104,'Rohit Verma', 'Agra', '9776655443',30,'Finance','J002','IT PROFF',14000,'1981-12-03'),
(105,'Rahul Gupta', 'Kanpur', '9123456789',20,'HR','J003','MANAGER', 28000,'1983-03-20');
SELECT * FROM EMPLOYEE;
Output:
2401330120023
Write SQL statements for the given queries.
1. MANAGER employees
Code:
SELECT Emp_no, E_name, Salary FROM EMPLOYEE WHERE Designation = 'MANAGER'; List
Emp_no, E_name, Salary of employees working as MANAGER
Output:
Code:
SELECT Emp_no, E_name, Designation, Salary FROM EMPLOYEE
WHERE Salary > ANY (SELECT Salary FROM EMPLOYEE WHERE Designation = 'IT PROFF');
Employees whose salary > any IT PROFF
Output:
Code:
SELECT Emp_no, E_name, Designation, Hiredate
FROM EMPLOYEE WHERE YEAR(Hiredate) > 1981
ORDER BY Designation ASC;
2401330120023
Output:
Code:
SELECT E_name, TIMESTAMPDIFF(YEAR, Hiredate, CURDATE())
AS Experience, ROUND(Salary/30, 2)
AS Daily_Salary FROM EMPLOYEE;
Output:
5. CLERK or ANALYST
Code:
SELECT Emp_no, E_name, Designation, Salary
FROM EMPLOYEE
WHERE Designation IN ('CLERK', 'ANALYST');
2401330120023
Output:
Code:
SELECT Emp_no, E_name, Hiredate FROM EMPLOYEE
WHERE Hiredate IN ('1981-05-01','1981-12-03','1981-12-17','1980-01-19');
7. Dept 10 or 20
Code:
SELECT * FROM EMPLOYEE WHERE Dept_no IN (10, 20);
Output:
Code:
SELECT E_name FROM EMPLOYEE WHERE E_name LIKE 'S%';
Code:
SELECT E_name, SUBSTRING(E_name,1,5) AS First_Five
FROM EMPLOYEE WHERE E_name LIKE 'H%';
2401330120023
Output:
Code:
SELECT Job_id, SUM(Salary) AS Total_Salary
FROM EMPLOYEE GROUP BY Job_id;
Output:
Code:
SELECT Dept_no, MIN(Salary) AS Min_Salary FROM EMPLOYEE GROUP BY Dept_no;
Code:
SELECT Dept_no, Dept_name, COUNT(*) AS Num_Employees
FROM EMPLOYEE GROUP BY Dept_no, Dept_name;
Code:
SELECT * FROM EMPLOYEE ORDER BY Salary ASC;
2401330120023
15. Salary > 16000 per dept
Code:
SELECT Dept_no, E_name, Salary FROM EMPLOYEE WHERE Salary > 16000 ORDER BY Dept_no;
Code:
ALTER TABLE EMPLOYEE ADD CONSTRAINT chk_empno CHECK (Emp_no > 100);
Code:
ALTER TABLE EMPLOYEE ADD CONSTRAINT uq_deptno UNIQUE (Dept_no);
18. PRIMARY KEY already defined on Emp_no during CREATE TABLE Output:
2401330120023
Program 9
Code:
CREATE TABLE science_student (id INT, name VARCHAR(50),
city VARCHAR(50),
dept VARCHAR(30));
CREATE TABLE commerce_student (id INT, name VARCHAR(50),
city VARCHAR(50),
dept VARCHAR(30));
INSERT INTO science_student VALUES (1,'Varun Shukla','Delhi','Science'),
(2,'Shivam Nishad','Lucknow','Science'),
(3,'Neha Sharma','Mumbai','Science');
INSERT INTO commerce_student VALUES (3,'Neha Sharma','Mumbai','Commerce'),
(4,'Vikas Rathore','Mumbai','Commerce'),
(5,'Rohit Verma','Delhi','Commerce'),
(6,'Rahul Gupta','Kanpur','Commerce');
Output:
UNION Operator
The UNION operator combines the result sets of two or more SELECT statements. It removes duplicate rows
from the result. Both SELECT statements must have the same number of columns with compatible data
types.
Code:
SELECT id, name, city FROM science_student UNION
SELECT id, name, city FROM commerce_student;
Output:
2401330120023
UNION ALL Operator
Code:
SELECT id, name, city FROM science_student UNION ALL
SELECT id, name, city FROM commerce_student;
UNION ALL returns all rows including duplicates from both SELECT statements.
Output:
INTERSECT Operator
Code:
SELECT [Link], [Link], [Link] FROM science_student s
INNER JOIN commerce_student c ON [Link] = [Link] AND [Link] = [Link];
The INTERSECT operator returns only the rows that appear in both SELECT statements. It gives common
records.
Output:
Code:
SELECT [Link], [Link], [Link] FROM science_students
LEFT JOIN commerce_student c
ON [Link] = [Link] WHERE [Link] IS NULL;
2401330120023
Output:
2401330120023
Program 10
Implementation of Queries using Inner Join: Natural Join, Equi Join & Non Equi Join, Outer Join.
Code:
CREATE TABLE dept (
dept_id INT PRIMARY KEY, dept_name VARCHAR(30), hod VARCHAR(50)
);
CREATE TABLE student (
Id INT PRIMARY KEY,
name VARCHAR(50),
city VARCHAR(50),
dept_id INT, salary INT
);
INSERT INTO dept VALUES
(10,'Science','Dr. Sharma'),(20,'Commerce','Dr. Verma'),
(30,'Arts','Dr. Gupta'),(40,'Maths','Dr. Singh');
INSERT INTO student VALUES (1,'Varun Shukla','Delhi',10,25000), (2,'Vikas
Rathore','Mumbai',20,15000),
(3,'Shivam Nishad','Lucknow',10,18000), (4,'Rohit Verma','Delhi',30,14000),
(5,'Rahul Gupta','Kanpur',20,28000), (6,'Neha Sharma','Mumbai',NULL,20000);
Output:
Natural Join
A NATURAL JOIN automatically joins tables based on columns with the same name and compatible data
types. No ON clause is needed.
Code:
SELECT * FROM student NATURAL JOIN dept;
Output:
2401330120023
Equi Join
An Equi Join is an inner join where rows from two tables are combined using the equality (=) operator on
related columns.
Code:
SELECT [Link], [Link], [Link], [Link], d.dept_name, [Link]
FROM student s, dept d
WHERE s.dept_id = d.dept_id;
Output:
Code:
SELECT [Link], [Link], [Link], d.dept_name
FROM student s, dept d
WHERE [Link] > 15000 AND s.dept_id != d.dept_id;
Output:
2401330120023
Outer Join
An Outer Join returns all rows from one or both tables, with NULL for non-matching rows.
Code:
SELECT [Link], [Link], [Link], [Link], d.dept_name
FROM student s LEFT OUTER JOIN dept d ON s.dept_id = d.dept_id;
Code:
SELECT [Link], [Link], [Link], d.dept_name
FROM student s RIGHT OUTER JOIN dept d ON s.dept_id = d.dept_id;
Code:
SELECT [Link], [Link], d.dept_name FROM student s LEFT JOIN dept d ON s.dept_id = d.dept_id UNION
SELECT [Link], [Link], d.dept_name FROM student s RIGHT JOIN dept d ON s.dept_id = d.dept_id;
Output:
LEFT OUTER JOIN – All rows from left table: RIGHT OUTER JOIN – All rows from right table.
2401330120023
Program 11
Implementation of Queries nested Queries or Sub Queries: IN, NOT IN, Exists, Not Exists, All and
Any.
IN Operator: The IN operator is used in a WHERE clause to check if a value matches any value in a
subquery or list.
Code:
-- IN Operator
SELECT name, salary FROM student
WHERE salary IN (SELECT salary FROM student WHERE dept_id = 10);
Output:
NOT IN Operator: The NOT IN operator returns rows where the value does not match any value in the
subquery result.
Code:
SELECT name, salary FROM student
WHERE salary NOT IN (SELECT salary FROM student WHERE dept_id = 20);
Output:
EXISTS Operator
The EXISTS operator returns TRUE if the subquery returns at least one row. It is used to check for the
existence of records
2401330120023
Code:
SELECT name, salary FROM student s WHERE EXISTS (
SELECT 1 FROM student s2
WHERE s2.dept_id = s.dept_id AND [Link] > 20000
);
Output:
Code:
SELECT name, salary FROM student s WHERE NOT EXISTS (
SELECT 1 FROM student s2
WHERE s2.dept_id = s.dept_id AND [Link] > 25000
);
Output:
ALL Operator
The ALL operator returns TRUE if the comparison is true for ALL values returned by the subquery.
Code:
SELECT name, salary FROM student
WHERE salary < ALL (SELECT salary FROM student WHERE dept_id = 10);
2401330120023
Output:
ANY Operator:
The ANY operator returns TRUE if the comparison is true for at least ONE value in the subquery.
Code:
SELECT name, salary FROM student
WHERE salary = ANY (SELECT salary FROM student WHERE dept_id = 20);
Output:
2401330120023
Program 12
Apply the theory operators, join's and nested queries on company database (Case Study-1). Write
the SQL Queries for the following statements.
Code:
CREATE TABLE DEPARTMENT (Dno INT PRIMARY KEY,
Dname VARCHAR(30),
MgrSSN VARCHAR(15),
MgrStartDate DATE);
CREATE TABLE EMPLOYEE (SSN VARCHAR(15) PRIMARY KEY,
Fname VARCHAR(20),
Lname VARCHAR(20),
Bdate DATE,
Address VARCHAR(60),
Sex CHAR(1),
Salary DECIMAL(10,2),
SuperSSN VARCHAR(15),
Dno INT);
CREATE TABLE PROJECT (Pno INT PRIMARY KEY,
Pname VARCHAR(30),
Plocation VARCHAR(30), Dno INT);
CREATE TABLE WORKS_ON (ESSN VARCHAR(15),
Pno INT,
Hours DECIMAL(5,1),
PRIMARY KEY (ESSN, Pno));
CREATE TABLE DEPENDENT (ESSN VARCHAR(15),
Dep_name VARCHAR(30),
Sex CHAR(1),
Bdate DATE,
Relationship VARCHAR(20));
Output:
Code:
SELECT [Link], [Link], [Link] FROM EMPLOYEE E
JOIN WORKS_ON W ON [Link] = [Link] JOIN PROJECT P ON [Link] = [Link]
WHERE [Link] = 5 AND [Link] = 'ProductX' AND [Link] > 10;
Employees in Dept 5 working >10 hrs on ProductX
2401330120023
Output:
Code:
SELECT [Link], [Link], D.Dep_name, [Link] FROM EMPLOYEE E
JOIN DEPENDENT D ON [Link] = [Link]
WHERE [Link] = D.Dep_name;
Output:
Code:
SELECT Fname, Lname, Salary, Dno FROM EMPLOYEE
WHERE SuperSSN = (SELECT SSN FROM EMPLOYEE
WHERE Fname='Franklin' AND Lname='Wong');
Output:
2401330120023
Total hours per week per project
Code:
SELECT [Link], [Link], SUM([Link]) AS Total_Hours
FROM PROJECT P JOIN WORKS_ON W
ON [Link] = [Link] GROUP BY [Link], [Link];
Output:
Code:
SELECT Fname, Lname FROM EMPLOYEE E
WHERE NOT EXISTS ( SELECT Pno FROM PROJECT WHERE Dno=5
EXCEPT SELECT Pno FROM WORKS_ON WHERE ESSN=[Link]);
Output:
2401330120023
Code:
SELECT DISTINCT [Link], [Link] FROM EMPLOYEE E
WHERE [Link] IN (SELECT ESSN FROM WORKS_ON)
AND (SELECT COUNT(DISTINCT Pno)
FROM WORKS_ON WHERE ESSN=[Link]) < (SELECT COUNT(*) FROM PROJECT);
Output:
Code:
SELECT [Link], [Link], AVG([Link]) AS Avg_Salary
FROM EMPLOYEE E JOIN DEPARTMENT D
ON [Link]=[Link] GROUP BY [Link], [Link];
Output:
Code:
SELECT AVG(Salary) AS Avg_Female_Salary
FROM EMPLOYEE WHERE Sex='F';
2401330120023
Output:
Code:
SELECT DISTINCT [Link], [Link], [Link], [Link], [Link] FROM EMPLOYEE E JOIN
WORKS_ON W ON [Link]=[Link] JOIN PROJECT P ON [Link]=[Link]
WHERE [Link]='Houston' AND [Link] NOT IN (SELECT Dno FROM PROJECT WHERE
Plocation='Houston');
Output:
2401330120023
Program 13
Implementation and apply all the set theory operators, join and nested queries concept on Case study.
Setup — Company Database (Case Study 1)
Code:
SELECT DISTINCT [Link],
[Link],
[Link] FROM EMPLOYEE E
JOIN WORKS_ON W ON [Link]=[Link] JOIN PROJECT P ON [Link]=[Link]
WHERE [Link] IN (SELECT Pno FROM WORKS_ON WHERE ESSN=(SELECT SSN FROM
EMPLOYEE WHERE
Fname='Scott')) UNION
SELECT DISTINCT [Link],
[Link],
[Link] FROM EMPLOYEE E
JOIN WORKS_ON W ON [Link]=[Link] JOIN PROJECT P ON [Link]=[Link] JOIN DEPARTMENT
D ON
[Link]=[Link]
WHERE [Link]=(SELECT SSN FROM EMPLOYEE WHERE Fname='Scott');
Output:
2401330120023
2. SSNs in dept 5 OR supervising dept-5 employee
Code:
SELECT SSN FROM EMPLOYEE WHERE Dno=5 UNION
SELECT DISTINCT SuperSSN FROM EMPLOYEE
WHERE SuperSSN IS NOT NULL AND Dno=5;
Output:
Code:
SELECT DISTINCT SuperSSN AS SSN FROM EMPLOYEE WHERE SuperSSN IS NOT NULL
AND SuperSSN NOT IN (SELECT MgrSSN FROM DEPARTMENT);
Output:
2401330120023
Code:
SELECT [Link], [Link], [Link] AS Manages
FROM EMPLOYEE E LEFT JOIN DEPARTMENT D ON [Link]=[Link];
Output:
Code:
SELECT [Link], [Link] FROM EMPLOYEE E
WHERE NOT EXISTS (SELECT 1 FROM DEPENDENT WHERE ESSN=[Link]);
Output:
Code:
SELECT [Link], [Link], COUNT(D.Dep_name) AS Dep_Count
FROM EMPLOYEE E JOIN DEPENDENT D
ON [Link]=[Link] GROUP BY [Link], [Link], [Link] HAVING
COUNT(D.Dep_name)>=2;
2401330120023
Output:
Code:
SELECT [Link], [Link], [Link] AS Dept_Managed FROM EMPLOYEE E
JOIN DEPARTMENT D ON [Link]=[Link]
WHERE [Link] IN (SELECT DISTINCT ESSN FROM DEPENDENT);
Output:
Code:
SELECT SSN, Fname, Lname, Dno, Salary
FROM EMPLOYEE WHERE SuperSSN IS NULL;
2401330120023
Output:
Code:
SELECT [Link], [Link], D.Dep_name, [Link] FROM EMPLOYEE E
JOIN DEPENDENT D ON [Link]=[Link] WHERE [Link]=D.Dep_name;
Output:
2401330120023
Program 14
Indexing
An INDEX is a database object that speeds up data retrieval operations. It creates an internal data structure
that allows the database engine to find rows faster without scanning the entire table. Setup – Student Table
Code:
CREATE TABLE student (
id INT PRIMARY KEY, name VARCHAR(50) NOT NULL,
age INT, city VARCHAR(50), dept VARCHAR(30), salary INT
);
Output:
Creating an Index
Code:
INSERT INTO student VALUES
(1,'Varun Shukla', 20,'Delhi', 'Science', 25000), (2,'Vikas Rathore',19,'Mumbai', 'Commerce',15000),
(3,'Shivam Nishad',21,'Lucknow','Science', 18000), (4,'Rohit Verma', 22,'Delhi', 'Commerce',28000),
(5,'Rahul Gupta', 20,'Kanpur', 'Arts', 14000),
(6,'Neha Sharma', 23,'Mumbai', 'Science', 20000);
Indexing
CREATE INDEX idx_city ON student (city); CREATE UNIQUE INDEX idx_name ON student (name);
CREATE INDEX idx_dept_salary ON student (dept, salary); SHOW INDEX FROM student;
Output:
2401330120023
Drop an Index
Code:
DROP INDEX idx_city ON student;
Output:
Views
A VIEW is a virtual table based on the result of a SELECT statement. It does not store data itself but presents
data from one or more tables.
Code:
CREATE VIEW science_students AS
SELECT id, name, age, city, salary FROM student
WHERE dept='Science'; SELECT * FROM science_students;
Output:
Code:
CREATE VIEW dept_salary_stats AS
SELECT dept, COUNT(*) AS Total, AVG(salary) AS Avg_Salary, MAX(salary) AS Max_Salary,
MIN(salary) AS Min_Salary
FROM student GROUP BY dept; SELECT * FROM dept_salary_stats;
2401330120023
Output:
Modifying a View
Code:
UPDATE science_students SET salary=26000 WHERE id=1; SHOW FULL TABLES WHERE
Table_type='VIEW';
Output:
Removing a View
Code:
DROP VIEW dept_salary_stats;
Output:
Sequence (PostgreSQL)
A SEQUENCE is a database object that generates a series of unique numeric values. It is commonly used to
auto-generate primary key values.
2401330120023
Creating a Sequence
Code:
CREATE TABLE orders (
order_id INT AUTO_INCREMENT PRIMARY KEY,
student_id INT, item VARCHAR(50), amount DECIMAL(8,2)
);
INSERT INTO orders(student_id, item, amount) VALUES (1,'Notebook',120.00),(2,'Pen
Set',45.00),(3,'Calculator',350.00),(1,'Bag',850.00);
SELECT * FROM orders;
Output:
Insert a Sequence
Code:
CREATE SEQUENCE roll_seq START WITH 1001 INCREMENT BY 1;
CREATE TABLE roll (roll_no INT PRIMARY KEY, name VARCHAR(50));
INSERT INTO roll VALUES (NEXT VALUE FOR roll_seq, 'Varun Shukla');
INSERT INTO roll VALUES (NEXT VALUE FOR roll_seq, 'Vikas Rathore');
INSERT INTO roll VALUES (NEXT VALUE FOR roll_seq, 'Shivam Nishad');
SELECT * FROM roll;
2401330120023
Output:
Removing a Sequence
Code:
ALTER SEQUENCE roll_seq RESTART WITH 2001;
DROP SEQUENCE roll_seq;
Output:
2401330120023
Program 15
PL/SQL Program to Add Two Numbers. PL/SQL (Procedural Language/SQL) extends SQL with
procedural constructs. Every PL/SQL block has a DECLARE, BEGIN, and END section.
Code:
DECLARE
a NUMBER := 10;
b NUMBER := 20; s NUMBER;
BEGIN
s := a + b; DBMS_OUTPUT.PUT_LINE('Sum = ' || s);
END;
/
Output: Sum = 30
Code:
DECLARE
a NUMBER := 0; b NUMBER := 1; c NUMBER; i NUMBER := 1; n NUMBER := 10;
BEGIN
DBMS_OUTPUT.PUT_LINE('Fibonacci Series:'); DBMS_OUTPUT.PUT_LINE(a);
DBMS_OUTPUT.PUT_LINE(b);
WHILE i <= n - 2 LOOP
c := a + b; DBMS_OUTPUT.PUT_LINE(c);
a := b; b := c; i := i + 1; END LOOP;
END;
/
2401330120023
Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Code:
DECLARE
a NUMBER := 25; b NUMBER := 40; c NUMBER := 30;
greatest NUMBER; BEGIN
IF a >= b AND a >= c THEN greatest := a; ELSIF b >= a AND b >= c THEN greatest := b; ELSE greatest
:= c;
END IF;
DBMS_OUTPUT.PUT_LINE('Greatest Number = ' || greatest); END;
/
Output: Greatest Number = 40
2401330120023
Program 16
Write a Pl/SQL code block to calculate the area of a circle for a value of radius varying from 3 to
7. Store the radius and the corresponding values of calculated area in an empty table named
Areas, consisting of two columns Radius and Area.
Concept:
Area of a circle = π × r² where π ≈ 3.14159
A FOR loop is used to iterate the radius from 3 to 7. Each calculated area is inserted into the AREAS
table.
Code:
CREATE TABLE AREAS (Radius NUMBER, Area NUMBER(10,4));
DECLARE
r NUMBER;
area NUMBER;
pi CONSTANT NUMBER := 3.14159265; BEGIN
FOR r IN 3..7 LOOP
area := pi * r * r;
INSERT INTO AREAS VALUES (r, ROUND(area, 4));
DBMS_OUTPUT.PUT_LINE('Radius: ' || r || ' | Area: ' || ROUND(area, 4)); END LOOP;
COMMIT;
END;
/
SELECT * FROM AREAS;
Output:
2401330120023
Program – 17
Create a row level trigger for the customers table that would fire for INSERT or UPDATE or
DELETE operations performed on the CUSTOMERS table. This trigger will display the salary
difference between the old values and new values.
A Row Level Trigger is a trigger that is executed once for each row affected by an INSERT, UPDATE,
or DELETE
operation on a table.
It fires automatically when a row is inserted, updated, or deleted.
It works on each row individually (not on whole table).
It can access old and new values using :OLD and :NEW.
Useful for auditing, validation, and tracking changes.
INSERT Trigger
An INSERT Trigger is a trigger that is fired automatically whenever a new record is inserted into a
table.
It executes after/before inserting a row.
It uses :NEW to access new values.
Useful for validating or displaying inserted data.
Code:
DELIMITER //
CREATE TRIGGER insert_salary_trigger AFTER INSERT ON customers
FOR EACH ROW BEGIN
INSERT INTO salary_log
VALUES (CONCAT('New Salary: ', [Link])); END //
DELIMITER ;
UPDATE Trigger
An UPDATE Trigger is fired automatically whenever an existing record is updated in a table.
It uses both :OLD and :NEW values.
Helps in tracking changes between old and new data.
Useful for auditing purposes.
2401330120023
DELIMITER //
DELIMITER :
DELETE Trigger
DELIMITER ;
2401330120023
Program 18
1. COMMIT
A COMMIT statement is used to permanently save all changes made during the current transaction in
the database
It makes all changes (INSERT, UPDATE, DELETE) permanent.
Once committed, changes cannot be undone.
It ensures data consistency after successful completion of operations.
START TRANSACTION:
UPDATE accounts
SET balance = balance - 1000 WHERE acc_id = 1;
UPDATE accounts
SET balance = balance + 1000 WHERE acc_id = 2; COMMIT;
Output:
2. ROLLBACK
A ROLLBACK statement is used to undo all changes made during the current transaction and restore
the database to its previous state .
It cancels all changes made after the last COMMIT.
Used when an error occurs during transaction.
Helps maintain data integrity
START TRANSACTION:
UPDATE accounts
SET balance = balance - 1000 WHERE acc_id = 1; ROLLBACK;
Output:
2401330120023
Program 19
Implementation of the MongoDB Shell Create Database (MongoDB Shell)
MONGOSH
use college show databases
Output:
Code:
[Link]({Name:"Jack",Age:23,City:"New York"})
{
acknowledged: true,
insertedId: ObjectId('67acb06850ceb99f7c526642')
}
[Link]({Name:"Alice",Age:20,City:"London"})
{
acknowledged: true,
insertedId: ObjectId('67acb10150ceb99f7c526643')
}
2401330120023
[Link]({Name:"Eve",Age:30,City:"London"})
{
acknowledged: true,
InsertedId: ObjectId('67acb12850ceb99f7c526644')
}
Output:
RENAME COLLECTION
Code:
[Link]("new_student")
{
ok: 1
}
db.new_student.find({})
{
_id: ObjectId('67acb06850ceb99f7c526642'), Name: 'Jack',
Age: 23,
City: 'New York'
}
2401330120023
{
_id: ObjectId('67acb10150ceb99f7c526643'), Name: 'Alice',
Age: 20,
City: 'London'
}
{
_id: ObjectId('67acb12850ceb99f7c526644'), Name: 'Eve',
Age: 30,
City: 'London'
}
Output:
DROP DATABASE
Code:
[Link](){ ok:1, dropped: ‘college’}
2401330120023
Output:
Code:
[Link]({Name:"Jack",Age:23,City:"New York"})
{
acknowledged: true,
insertedId: ObjectId('67acb45150ceb99f7c526645')
}
[Link]({Name:"Alice",Age:20,City:"London"})
{
acknowledged: true,
insertedId: ObjectId('67acb45e50ceb99f7c526646')
}
[Link]({Name:"Eve",Age:30,City:"London"})
{
acknowledged: true,
insertedId: ObjectId('67acb46a50ceb99f7c526647')
}
[Link]({})
{
_id: ObjectId('67acb45150ceb99f7c526645'), Name: 'Jack',
Age: 23,
City: 'New York'
}
{
_id: ObjectId('67acb45e50ceb99f7c526646'), Name: 'Alice',
Age: 20,
City: 'London'
}
2401330120023
Output:
2401330120023
Program 20
Implementation of the CRUD Operation in MongoDB
Code:
use admin
[Link]([
{ name: "Alice", age: 30, city: "New York" },
{ name: "Bob", age: 25, city: "Los Angeles" }
]);
Output:
READ OPERATION
A Read Operation is used to retrieve data from a collection.
find() method is used to fetch data
It can filter data using conditions
Returns documents matching the query
Code:
[Link]({ city: "New York" });
Output:
UPDATE OPERATION
An Update Operation is used to modify existing documents in a collection.
updateOne() is used to update a single document
$set operator is used to change values
Helps in modifying existing data
2401330120023
Code:
[Link](
{ name: "Alice" },
{ $set: { city: "San Francisco" } }
);
Output:
DELETE OPERATION
A Delete Operation is used to remove documents from a collection. deleteOne() is
used to delete a single document
Removes data permanently
Condition is required to select the document
Code:
[Link]({ name: "Bob" });
Output:
2401330120023