DBMS Lab Record

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

INDEX

SL NO Date Name of the Experiment Page No

1 23/07/24 Database schema for 6


application with ER diagram

2 05/08/24 Practice SQL commands for 8


DML

3 12/08/24 Nested and Join queries 16

4 19/08/24 Order by, Group by, Having 24


clauses

5 24/08/24 View and Triggers 30

6 02/09/24 Built-in and Aggregate 32


Functions

7 23/09/24 Practice of SQL TCL 37


Commands

8 27/09/24 PL/SQL Programs 41

9 27/09/24 PL/SQL Cursors and 47


Exceptions

10 30/09/24 SQL Procedures and Functions 51

11 14/10/24 MongoDB Queries 59

12 04/11/24 Project 67

5
Experiment No:1 Date:23/07/24

Database schema for application with ER diagram

Aim:

a) Design a database schema for an application with ER diagram

b) Creation, modification, configuration, and deletion of databases using SQL

Program 1:

Design a normalized database schema for the following requirement

The requirement:

A hospital token management system to make a token for the patient which keeps track
of doctors,doctors department,patient name,patient age,patient gender.

When the patient enters the system the system provides a guided way to register the
patient then book the doctor as a token number in return.

Database Design

Doctor(doctorID, Dname, Ddept)

Patient(PId,PName,PAge,PGender)

Token(tokenId, date, doctorId, Pid)

DDL COMMANDS:

6
mysql> create table Doctor (doctorID int primary key, Dname varchar(255) not null,
Ddept varchar(255) not null );

mysql> create table Patient (PID int primary key, Pname varchar(255) not null, Page int
not null, PGender varchar(10) not null );

mysql> create table Token (tokenID int primary key, tdate DATE not null, doctorID int,
PID int, foreign key (doctorID) references Doctor(doctorID), foreign key (PID)
references Patient(PID) );

Result:

A normalized database schema created.

Program 2:
Create an ER diagram for the above database design .

ER DIAGRAM :

Result:
ER diagram for the above database design created.

7
Experiment No:2 Date:05/08/24

Practice SQL commands for DML

AIM:
Practice SQL commands for DML (insertion, updating, altering, deletion of data,
and viewing/querying records based on condition in databases)

Consider the employee database given below

emp (emp_id,emp_name, Street_No, city)

works (emp_id, company name, salary)

company (company name, city)

manages (emp_id, manager_id)

Note: Emp_id should start with ‘E’ in Emp table and emp_id in works table must be the
emp_id from emp table . emp_id and manager_id in manages table must be the emp_id
from emp table

I. Add these four tables with sufficient constraints.

II. Alter table emp add a constraint that emp_name cannot be null

III. Export ER diagram from database and verify relationships.

8
Consider the employee database created for the following questions

a. Find the names of all employees who work for SBI.

b. Find all employees in the database who live in the same cities as the companies for

which they work.

c. Find all employees and their managers in the database who live in the same cities and
on the same street number as do their managers.

d. Find all employees who earn more than the average salary of all employees of their

company.

e. Find the company that pay least total salary along with the salary paid.

f. Give all managers of SBI a 10 percent raise.

g. Find the company that has the most employees

h. Find those companies whose employees earn a higher salary, on average than the

average salary at Indian Bank.

i. Query to find name and salary of all employees who earn more than each employee

of ‘Indian Bank’

DDL:

mysql> create database cmpy;


Query OK, 1 row affected (0.01 sec)

9
mysql> use cmpy;
Database changed
mysql> CREATE TABLE emp (
-> emp_id VARCHAR(10) PRIMARY KEY CHECK(emp_id LIKE 'E%'),
-> emp_name VARCHAR(50) NOT NULL,
-> Street_No VARCHAR(10),
-> city VARCHAR(50)
-> );
Query OK, 0 rows affected (0.04 sec)

mysql> CREATE TABLE company (


-> company_name VARCHAR(50) PRIMARY KEY,
-> city VARCHAR(50)
-> );
Query OK, 0 rows affected (0.03 sec)

mysql> CREATE TABLE works (


-> emp_id VARCHAR(10),
-> company_name VARCHAR(50),
-> salary DECIMAL(10, 2),
-> FOREIGN KEY (emp_id) REFERENCES emp(emp_id),
-> FOREIGN KEY (company_name) REFERENCES company(company_name)
-> );
Query OK, 0 rows affected (0.04 sec)

mysql> CREATE TABLE manages (


-> emp_id VARCHAR(10),
-> manager_id VARCHAR(10),
-> FOREIGN KEY (emp_id) REFERENCES emp(emp_id),
-> FOREIGN KEY (manager_id) REFERENCES emp(emp_id)
-> );
Query OK, 0 rows affected (0.04 sec)

mysql> ALTER TABLE emp


-> MODIFY emp_name VARCHAR(50) NOT NULL;
Query OK, 0 rows affected (0.02 sec)

10
Records: 0 Duplicates: 0 Warnings:0

mysql> INSERT INTO emp (emp_id, emp_name, Street_No, city) VALUES


-> ('E101', 'John', '12', 'Delhi'),
-> ('E102', 'Alice', '15', ‘Kolkata'),
-> ('E103', 'Raj', '12', 'Delhi'),
-> ('E104', 'Mike', '20', 'Delhi'),
-> ('E105', 'Sara', '15', 'Mumbai'),
-> ('E106', 'Tom', '12', 'Delhi');
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0

mysql> INSERT INTO company (company_name, city) VALUES


-> ('SBI', 'Delhi'),
-> ('Indian Bank', 'Mumbai'),
-> ('HDFC', 'Delhi');
Query OK, 3 rows affected (0.01 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> INSERT INTO works (emp_id, company_name, salary) VALUES


-> ('E101', 'SBI', 50000),
-> ('E102', 'SBI', 60000),
-> ('E103', 'Indian Bank', 45000),
-> ('E104', 'HDFC', 70000),
-> ('E105', 'Indian Bank', 55000),
-> ('E106', 'SBI', 40000);
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0

mysql> INSERT INTO manages (emp_id, manager_id) VALUES


-> ('E101', 'E103'),
-> ('E102', 'E101'),
-> ('E105', 'E102'),
-> ('E106', 'E101');
Query OK, 4 rows affected (0.01 sec)

11
Records: 4 Duplicates: 0 Warnings: 0

12
Query:

a. Find the names of all employees who work for SBI.

mysql> SELECT emp_name


-> FROM emp
-> JOIN works ON emp.emp_id = works.emp_id
-> WHERE works.company_name = 'SBI';

emp_name

John

Alice

2 rows in set (0.00 sec)

b. Find all employees in the database who live in the same cities as the companies for
which they work.

mysql> SELECT emp.emp_name


-> FROM emp
-> JOIN works ON emp.emp_id = works.emp_id
-> JOIN company ON works.company_name = company.company_name
-> WHERE emp.city = company.city;
+-------------+
| emp_name |
+-------------+
| Mike |
| Sara |
| John |
+-------------+

3 rows in set (0.00 sec)

c. Find all employees and their managers in the database who live in the same cities
and on the same street number as do their managers.

13
mysql> SELECT e1.emp_name AS Employee, e2.emp_name AS Manager
-> FROM emp e1
-> JOIN manages m ON e1.emp_id = m.emp_id
-> JOIN emp e2 ON m.manager_id = e2.emp_id
-> WHERE e1.city = e2.city AND e1.Street_No = e2.Street_No;
+-----------+------------+
| Employee | Manager |
+-----------+------------+
| John | Raj |
| Tom | John |
+-----------+------------+
2 rows in set (0.00 sec)

d. Find all employees who earn more than the average salary of all employees of
their company.

mysql> SELECT emp_name, salary


-> FROM emp
-> JOIN works ON emp.emp_id = works.emp_id
-> WHERE salary > (
-> SELECT AVG(salary)
-> FROM works AS w
-> WHERE w.company_name = works.company_name
-> );
+--------------+--------------+
| emp_name | salary |
+-------------+--------------+
| Alice | 60000.00 |
| Sara | 55000.00 |
+------------+---------------+
2 rows in set (0.00 sec)

e. Find the company that pays the least total salary along with the salary paid.
mysql> SELECT company_name, SUM(salary) AS total_salary
-> FROM works

14
-> GROUP BY company_name
-> ORDER BY total_salary ASC
-> LIMIT 1;
+-------------------+-----------------+
| company_name | total_salary |
+-------------------+-----------------+
| HDFC | 70000.00 |
+-------------------+-----------------+
1 row in set (0.00 sec)

f. Give all managers of SBI a 10 percent raise.

mysql> UPDATE works


-> SET salary = salary * 1.1
-> WHERE company_name = 'SBI'
-> AND emp_id IN (SELECT manager_id FROM manages);
Query OK, 2 rows affected (0.01 sec)
Rows matched: 2 Changed: 2 Warnings: 0

h. Find those companies whose employees earn a higher salary, on average, than the
average salary at Indian Bank.

mysql> SELECT company_name


-> FROM works
-> GROUP BY company_name
-> HAVING AVG(salary) > (
-> SELECT AVG(salary)
-> FROM works
-> WHERE company_name = 'Indian Bank'
-> );
+-------------------+
| company_name |
+-------------------+
| HDFC |
| SBI |
+-------------------+
2 rows in set (0.00 sec)

15
i. Query to find the name and salary of all employees who earn more than each
employee of ‘Indian Bank’.

mysql> SELECT emp_name, salary


-> FROM emp
-> JOIN works ON emp.emp_id = works.emp_id
-> WHERE salary > ALL (
-> SELECT salary
-> FROM works
-> WHERE company_name = 'Indian Bank'
-> );
+-------------+------------+
| emp_name | salary |
+-------------+------------+
| Alice | 66000.00 |
| Mike | 70000.00 |
+-------------+------------+
2 rows in set (0.00 sec)

Result:
DML Statements have been executed.

16
Experiment No:3 Date:12/08/24

Nested and Join queries

AIM

Implementation of set operators nested queries, and join queries

1. Make a list of all project numbers for projects that involve an employee whose last
name is 'Raj' as a worker or as a manager of the department that controls the project.

2. Retrieve the name of each employee who has a dependent with the same name as
the employee.

17
3. Retrieve the names of employees who have no dependents.

4. Retrieve the social security numbers of all employees who work on project
number 1, 2, or 3.

5. Retrieve the names of all employees who do not have supervisors.

6. Delete the department number 3 from the database.

7. Change the location and controlling department number of project number 10 to


'Kerala' and 5, respectively.

DDL:

mysql> create table EMPLOYEE(FNAME varchar(20) NOT NULL,MINT


varchar(20),LNAME varchar(20), SSN int primary key,BDATE DATE, ADDRESS
varchar(50),SEX varchar(10),SALARY float,SUPERSSN int,DNO int);
Query OK, 0 rows affected (0.02 sec)

mysql> create table DEPARTMENT(DNAME varchar(25) NOT NULL,DNUMBER int


primary key,MGRSSN int,MGRSTARTDATE date,Foreign key(MGRSSN) references
EMPLOYEE(SSN) on delete cascade on update cascade);
Query OK, 0 rows affected (0.03 sec)

mysql> create table DEPT_LOCATIONS(DNUMBER int,DLOCATION


varchar(30),primary key(DNUMBER,DLOCATION),foreign key(DNUMBER)
references DEPARTMENT(DNUMBER) on delete cascade on update cascade);

mysql> create table PROJECT(PNAME varchar(30),PNUMBER int primary


key,PLOCATION varchar(30),DNUM int,foreign key(DNUM) references
DEPARTMENT(DNUMBER) on delete cascade on update cascade);
Query OK, 0 rows affected (0.03 sec)

mysql> create table WORKS_ON(ESSN int,PNO int,HOURS int ,primary


key(ESSN,PNO),foreign key(ESSN) references EMPLOYEE(SSN) on delete cascade on

18
mysql> update cascade,foreign key(PNO) references PROJECT(PNUMBER) on delete
cascade on update cascade);
Query OK, 0 rows affected (0.02 sec)

mysql> create table WORKS_ON(ESSN int,PNO int,HOURS int ,primary


key(ESSN,PNO),foreign key(ESSN) references EMPLOYEE(SSN) on delete cascade on
update cascade,foreign key(PNO) references PROJECT(PNUMBER) on delete cascade
on update cascade);
Query OK, 0 rows affected (0.02 sec)

mysql> Alter table EMPLOYEE ADD foreign key(DNO) references


DEPARTMENT(DNUMBER) on delete cascade on update cascade;
Query OK, 0 rows affected (0.06 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> INSERT INTO EMPLOYEE (FNAME, MINT, LNAME, SSN, BDATE,


ADDRESS, SEX, SALARY, SUPERSSN, DNO) VALUES ('John', 'A', 'Doe', 111111111,
'1980-01-01', 'MG Road, Mumbai', 'M', 50000, NULL, 1), ('Raj', 'K', 'Singh', 222222222,
'1985-02-15', 'Connaught Place, Delhi', 'M', 60000, 111111111, 3), ('Mira', 'L', 'Raj',
333333333, '1990-03-10', 'Koramangala, Bangalore', 'F', 45000, 222222222, 3), ('Sanjay',
'M', 'Raj', 444444444, '1992-04-20', 'Indiranagar, Bangalore', 'M', 55000, 111111111, 2),
('Rani', 'N', 'Patel', 555555555, '1988-05-25', 'T Nagar, Chennai', 'F', 62000, NULL, 4),
('Amit', 'O', 'Shah', 666666666, '1979-06-30', 'Marine Drive, Mumbai', 'M', 48000,
111111111, 5), ('Anita', 'P', 'Verma', 777777777, '1982-07-15', 'Fort Kochi, Kerala', 'F',
47000, NULL, 5), ('Mohit', 'Q', 'Gupta', 888888888, '1991-08-19', 'Sector 62, Noida', 'M',
52000, 666666666, 2);

mysql> INSERT INTO DEPARTMENT (DNAME, DNUMBER,


MGRSSN,MGRSTARTDATE)
-> VALUES
-> ('Research', 1, 111111111, '2010-01-01'),
-> ('Administration', 2, 444444444, '2011-02-15'),
-> ('Sales', 3, 222222222, '2012-03-10'),
-> ('IT', 4, 555555555, '2013-04-20'),
-> ('HR', 5, 666666666, '2014-05-25');
Query OK, 5 rows affected (0.00 sec)
Records: 5 Duplicates: 0 Warnings: 0

19
mysql> INSERT INTO DEPT_LOCATIONS (DNUMBER, DLOCATION)
-> VALUES
-> (1, 'Mumbai'),
-> (2, 'Delhi'),
-> (3, 'Bangalore'),
-> (4, 'Chennai'),
-> (5, 'Kerala');
Query OK, 5 rows affected (0.00 sec)
Records: 5 Duplicates: 0 Warnings: 0

mysql> INSERT INTO PROJECT (PNAME, PNUMBER, PLOCATION, DNUM)


-> VALUES
-> ('Alpha', 1, 'Mumbai', 1),
-> ('Beta', 2, 'Delhi', 2),
-> ('Gamma', 3, 'Bangalore', 3),
-> ('Delta', 4, 'Chennai', 4),
-> ('Epsilon', 5, 'Kerala', 5),
-> ('Zeta', 10, 'Kerala', 5);
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0

mysql> INSERT INTO WORKS_ON (ESSN, PNO, HOURS)


-> VALUES
-> (111111111, 1, 10),
-> (222222222, 2, 20),
-> (333333333, 3, 15),
-> (444444444, 3, 25),
-> (555555555, 4, 30),
-> (666666666, 5, 35),
-> (777777777, 1, 20),
-> (888888888, 2, 40),
-> (444444444, 1, 10),
-> (222222222, 10, 15);
Query OK, 10 rows affected (0.02 sec)
Records: 10 Duplicates: 0 Warnings: 0

20
INSERT INTO DEPENDENT (ESSN, DEPENDENT_NAME, SEX, BDATE,
RELATIONSHIP) VALUES (111111111, 'John', 'M', '2010-01-01', 'Son'), (222222222
, 'Raj', 'M', '2015-05-15', 'Son'), (333333333, 'Mira', 'F', '2012-03-10', 'Daughter'),
(444444444, 'Sanjay', 'M', '1992-04-20', 'Self'), (5555
), (888888888, 'Ravi', 'M', '2011-08-19', 'Son');
Query OK, 8 rows affected (0.01 sec)
Records: 8 Duplicates: 0 Warnings: 0

Query:

1. Make a list of all project numbers for projects that involve an employee
whose last

SELECT P.PNUMBER FROM PROJECT AS P WHERE P.DNUM IN ( SELECT


D.DNUMBER FROM DEPARTMENT D JOIN EMPLOYEE E ON D.MGRSSN =
E.SSN WHERE E.LNAME = 'Raj' ) OR P.PNUMBER IN ( SELECT W.PNO
FROM WORKS_ON W JOIN EMPLOYEE E ON W.ESSN = E.SSN WHERE
E.LNAME ='Raj' );

+---------------+
| PNUMBER |
+--------------+
| 1 |
| 2 |
| 3 |
+--------------+

2.Retrieve the name of each employee who has a dependent with the same name as
the employee.

SELECT E.FNAME FROM EMPLOYEE AS E JOIN DEPENDENT AS D ON E.SSN


= D.ESSN WHERE E.FNAME = D.DEPENDENT_NAME;

21
+------------+
| FNAME |
+------------+
| John |
| Raj |
| Mira |
| Sanjay |
| Amit |
+----------+

3.Retrieve the names of employees who have no dependents.

mysql> SELECT FNAME, LNAME FROM EMPLOYEE AS E WHERE NOT EXISTS(


SELECT ESSN FROM DEPENDENT AS D WHERE E.SSN = D.ESSN );
+-----------+-----------+
| FNAME | LNAME |
+-----------+----------+
| Anita | Verma |
+-----------+----------+
1 row in set (0.00 sec)

4.Retrieve the social security numbers of all employees who work on project number
1, 2, or 3.

mysql>SELECT ESSN FROM WORKS_ON WHERE PNO IN (1,2,3);


+--------------+
| ESSN |
+--------------+
| 111111111 |
| 444444444 |
| 777777777 |
| 222222222 |
| 888888888 |
| 333333333 |
| 444444444 |
+--------------+
7 rows in set (0.00 sec)

22
5.Retrieve the names of all employees who do not have supervisors.

mysql>SELECT SSN,FNAME FROM EMPLOYEE WHERE SUPERSSN IS NULL;


+-------------+-----------+
| SSN | FNAME |
+-------------+-----------+
| 111111111 | John |
| 555555555 | Rani |
| 777777777 | Anita |
+-------------+-----------+
3 rows in set (0.00 sec)

6. Delete the department number 3 from the database.

mysql>DELETE FROM DEPARTMENT WHERE DNUMBER=3;


Query OK, 1 row affected (0.01 sec)

SELECT * FROM DEPARTMENT;

+--------------------+----------------+---------------+-----------------------+
| DNAME | DNUMBER | MGRSSN | MGRSTARTDATE |
+--------------------+----------------+---------------+------------------------+
| Research | 1 | 111111111 | 2010-01-01 |
| Administration | 2 | 444444444 | 2011-02-15 |
| IT | 4 | 555555555 | 2013-04-20 |
| HR | 5 | 666666666 | 2014-05-25 |
+-------------------+----------------+---------------+------------------------+

7.Change the location and controlling department number of project number 10 to


'Kerala' and 5, respectively.

mysql> UPDATE PROJECT SET PLOCATION="Kerala",DNUM=5 WHERE


PNUMBER=10;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0

23
mysql> SELECT * FROM PROJECT;
+------------+---------------+------------------+---------+
| PNAME | PNUMBER | PLOCATION | DNUM |
+------------+---------------+-----------------+----------+
| Alpha | 1 | Mumbai | 1 |
| Beta | 2 | Delhi | 2 |
| Delta | 4 | Chennai | 4 |
| Epsilon | 5 | Kerala | 5 |
| Zeta | 10 | Kerala | 5 |
+------------+--------------+------------------+----------+
5 rows in set (0.00 sec)

Result:
Different nested and join queries have been executed

24
Experiment No:4 Date:19/08/24

Order by, Group by, Having clauses

AIM

Implementation of various aggregate functions in SQL

Implementation of Order By, Group By & Having clause

1. Find the maximum salary, the minimum salary, and the average salary among
employees who work for the 'Research' department.

2. For each department, retrieve the department number, the number of employees in
the department, and their average salary.

3. For each project, retrieve the project number, project name, and the number of
employees who work on that project.

4. For each project on which more than two employees work, retrieve the project
number, project name, and the number of employees who work on that project.

5. Retrieve all employees who live in Delhi.

6. Retrieve all employees who were born in January.

7. Retrieve a list of employees and the projects each works in, ordered by the
employee's department, and within each department ordered alphabetically by employee
last name.

8. Retrieve the details of the employee getting the third highest salary.

9. List all the employees born on “Saturday”.

25
10. Find the average age of employees.

11. List all the employees born on 1st of any month.

12. List the employee name and reverse of the name

Query:

1.Find the maximum salary, the minimum salary, and the average salary among
employees who work for the 'Research' department.

SELECT MAX(E.SALARY) AS MAX_SALARY,MIN(E.SALARY) AS


MIN_SALARY,AVG(E.SALARY) AS AVG_SALARY FROM EMPLOYEE AS E JOIN
DEPARTMENT AS D ON E.DNO=D.DNUMBER WHERE DNAME="Research";
+---------------------+--------------------+---------------------+
| MAX_SALARY | MIN_SALARY | AVG_SALARY |
+---------------------+--------------------+---------------------+
| 50000 | 50000 | 50000 |
+---------------------+--------------------+---------------------+
1 row in set (0.01 sec)

2.For each department, retrieve the department number, the number of employees
in the department, and their average salary.

Select D.DNUMBER,COUNT(E.SSN),AVG(E.SALARY) as Average_Salary from


DEPARTMENT AS D JOIN EMPLOYEE AS E ON E.DNO=D.DNUMBER GROUP
BY D.DNU
MBER;
+----------------+-----------------------+----------------------+
| DNUMBER | COUNT(E.SSN) | Average_Salary |
+----------------+-----------------------+----------------------+
| 1 | 1 | 50000 |
| 2 | 2 | 53500 |
| 4 | 1 | 62000 |
| 5 | 2 | 47500 |
+----------------+-----------------------+----------------------+
4 rows in set (0.00 sec)

26
3.For each project, retrieve the project number, project name, and the number of
employees who work on that project.
SELECT P.PNUMBER,P.PNAME,COUNT(W.ESSN) FROM PROJECT AS P JOIN
WORKS_ON AS W ON P.PNUMBER=W.PNO GROUP BY P.PNUMBER;
+---------------+------------- +--------------------------+
| PNUMBER | PNAME | COUNT(W.ESSN) |
+---------------+------------- +-------------------------+
| 1 | Alpha | 3 |
| 2 | Beta | 1 |
| 4 | Delta | 1 |
| 5 | Epsilon | 1 |
+---------------+--------------+-------------------------+
4 rows in set (0.01 sec)

4.For each project on which more than two employees work, retrieve the project
number, project name, and the number of employees who work on that project.

SELECT P.PNUMBER,P.PNAME,COUNT(W.ESSN) FROM PROJECT AS P JOIN


WORKS_ON AS W ON P.PNUMBER=W.PNO GROUP BY P.PNUMBER HAVING
COUNT(ESSN)>2;
+----------------+-----------+--------------------------+
| PNUMBER | PNAME | COUNT(W.ESSN) |
+----------------+-----------+--------------------------+
| 1 | Alpha | 3 |
+----------------+-----------+--------------------------+
1 row in set (0.01 sec)

5. Retrieve all employees who live in Delhi.

SELECT SSN,FNAME FROM EMPLOYEE WHERE ADDRESS LIKE "%Mumbai%";


+----------------+-----------+
| SSN | FNAME |
+----------------+-----------+
| 111111111 | John |
| 666666666 | Amit |
+----------------+------------+

27
2 rows in set (0.00 sec)

6.Retrieve all employees who were born in January.

SELECT SSN,FNAME FROM EMPLOYEE WHERE


MONTHNAME(BDATE)="January";
+--------------+------------+
| SSN | FNAME |
+--------------+-----------+
| 111111111 | John |
+--------------+-----------+
1 row in set (0.00 sec)

7.Retrieve a list of employees and the projects each works in, ordered by the
employee's department, and within each department ordered alphabetically by
employee last name.

>SELECT E.FNAME,P.PNAME,D.DNUMBER,D.DNAME FROM EMPLOYEE AS


E,DEPARTMENT AS D,PROJECT AS P,WORKS_ON AS W WHERE
E.DNO=D.DNUMBER AND P.PNUMBER=W.PNO AND W.ESSN=E.SSN GROUP
BY D.DNUMBER,D.DNAME,E.FNAME,P.PNAME ORDER BY
D.DNAME,E.FNAME;

+------------+--------------+---------------+----------------------+
| FNAME | PNAME | DNUMBER | DNAME |
+------------+---------- --+----------------+--------------------- +
| Mohit | Beta | 2 | Administration |
| Sanjay | Alpha | 2 | Administration |
| Amit | Epsilon | 5 | HR |
| Anita | Alpha | 5 | HR |
| Rani | Delta | 4 | IT |
| John | Alpha | 1 | Research |
+-------------+------------+-----------------+------------------—-+
6 rows in set (0.00 sec)

28
8.Retrieve the details of the employee getting the third highest salary.

SELECT SSN,FNAME,SALARY FROM EMPLOYEE ORDER BY SALARY DESC


LIMIT 1 OFFSET 2;
+----------------+------------+------------+
| SSN | FNAME | SALARY |
+---------------+------------+-------------+
| 888888888 | Mohit | 52000 |
+---------------+------------+-------------+
1 row in set (0.00 sec)

9.List all the employees born on “Saturday”.

SELECT E.SSN,E.FNAME FROM EMPLOYEE AS E WHERE


DAYNAME(BDATE)="saturday";
+---------------+-----------+
| SSN | FNAME |
+---------------+-----------+
| 666666666 | Amit |
+---------------+-----------+
1 row in set (0.00 sec)

10.Find the average age of employees.

SELECT AVG(TIMESTAMPDIFF(YEAR,BDATE,CURDATE())) AS AVERAGE_AGE


FROM EMPLOYEE;
+-----------------------+
| AVERAGE_AGE |
+-----------------------+
| 38.6667 |
+-----------------------+
1 row in set (0.00 sec)

11. List all the employees born on 1st of any month.

29
SELECT E.SSN,E.FNAME FROM EMPLOYEE AS E WHERE
DAYOFMONTH(BDATE)=01;

+-----------------+-----------+
| SSN | FNAME |
+----------------+------------+
| 111111111 | John |
+----------------+------------+
1 row in set (0.00 sec)

12.List the employee name and reverse of the name.

SELECT FNAME,REVERSE(FNAME) FROM EMPLOYEE;


+--------------+----------------------------+
| FNAME | REVERSE(FNAME) |
+--------------+----------------------------+
| John | nhoJ |
| Sanjay | yajnaS |
| Rani | inaR |
| Amit | timA |
| Anita | atinA |
| Mohit | tihoM |
+-------------+-----------------------------+
6 rows in set (0.00 sec)

Result:
DML Statements have been executed.

30
Experiment No:5 Date:24/08/24

View and Triggers

AIM
Practice of SQL commands for creation of views and triggers

1.Create a view which contains Department name, number of employees in that


department and the total salary paid by each department

2. Create a trigger to check , whether an employee’s salary is greater than the salary of
his or her direct supervisor in the COMPANY database.

Query:

1.Create a view which contains Department name, number of employees in that


department and the total salary paid by each department.

create view DEPTVIEW AS(Select D.DNAME,count(E.SSN) AS


NO_OF_EMP,SUM(E.SALARY) AS SUM_OF_SALARY from DEPARTMENT AS D
JOIN EMPLOYEE AS E ON D.DNUMBER=E.DNO GROUP BY D.DNUMBER);
Query OK, 0 rows affected (0.01 sec)

mysql> SELECT * FROM DEPTVIEW;


+----------------------+-------------------+---------------------------+
| DNAME | NO_OF_EMP | SUM_OF_SALARY |
+----------------------+--------------------+---------------------------+
| Research | 1 | 50000 |
| Administration | 2 | 107000 |
| IT | 1 | 62000 |
| HR | 2 | 95000 |
+---------------------+---------------------+----------------------------+
4 rows in set (0.01 sec)

2. Create a trigger to check , whether an employee’s salary is greater than the


salary of his or her direct supervisor in the COMPANY database.

31
CREATE TABLE ERROR(SSN INT,SUPERSSN INT,FOREIGN KEY(SSN) REFERENCES
EMPLOYEE(SSN),FOREIGN KEY(SUPERSSN) REFERENCES EMPLOYEE(SSN));
Query OK, 0 rows affected (0.03 sec)

DELIMITER //
mysql> CREATE TRIGGER CHECK_SALARY
-> AFTER INSERT ON EMPLOYEE
-> FOR EACH ROW
-> BEGIN
-> IF NEW.SUPERSSN IS NOT NULL THEN
-> IF(SELECT SALARY FROM EMPLOYEE WHERE
SSN=NEW.SUPERSSN)<NEW.SALARY THEN
-> INSERT INTO ERROR(SSN,SUPERSSN) VALUES(NEW.SSN,NEW.SUPERSSN);
-> SIGNAL SQLSTATE '45000'
-> SET MESSAGE_TEXT = "EMPLOYEE SALARY CANNOT EXCEED SUPERVISOR
SALARY!";
-> END IF;
-> END IF;
-> END //

INSERT INTO EMPLOYEE VALUES("Aarav","M","Singh",333333333,"1995-07-10","MG


Road,Bangalore","M",69000,111111111,1);
ERROR 1644 (45000): EMPLOYEE SALARY CANNOT EXCEED SUPERVISOR SALARY!

Result:
Views and Triggers have been executed.

32
Experiment No:6 Date:02/09/24

Built-in and Aggregate Functions

AIM

Implementation of built-in functions in RDBMS.

Implementation of various aggregate functions in SQL.


Query:
mysql> select abs(-50);
+------------+
| abs(-50) |
+------------+
| 50 |
+------------+
1 row in set (0.00 sec)

mysql> Select mod(10,4);


+--------------+
| mod(10,4) |
+--------------+
| 2 |
+--------------+
1 row in set (0.00 sec)

mysql> Select pow(4,2);


+------------+
| pow(4,2) |
+----------- +
| 16 |
+------------+
1 row in set (0.00 sec)

33
mysql> Select sqrt(16);
+----------+
| sqrt(16) |
+----------+
| 4 |
+----------+
1 row in set (0.00 sec)

mysql> Select greatest(2,5,18,6,13);


+-------------------------+
| greatest(2,5,18,6,13) |
+-------------------------+
| 18 |
+-------------------------+
1 row in set (0.00 sec)

mysql> Select least(2,5,18,6,13);


+---------------------+
| least(2,5,18,6,13) |
+---------------------+
| 2 |
+--------------------+
1 row in set (0.00 sec)

mysql> Select truncate(22.897,2);


+----------------------+
| truncate(22.897,2) |
+----------------------+
| 22.89 |
+----------------------+
1 row in set (0.00 sec)

mysql> Select round(22.897,2);

34
+--------------------+
| round(22.897,2) |
+---------------------+
| 22.90 |
+---------------------+
1 row in set (0.00 sec)

mysql> SELECT LOWER('INDIA') AS lowercase;


+------------+
| lowercase |
+------------+
| india |
+-----------+
1 row in set (0.00 sec)

mysql> SELECT UPPER('india') AS uppercase;


+-----------+
| uppercase |
+-----------+
| INDIA |
+-----------+
1 row in set (0.00 sec)

mysql> SELECT CHAR_LENGTH('India');


+-------------------------------+
| CHAR_LENGTH('India') |
+-------------------------------+
| 5 |
+--------------------------------+
1 row in set (0.00 sec)

35
SELECT CURRENT_DATE FROM DUAL;
+-----------------------+
| CURRENT_DATE |
+-----------------------+
| 2024-11-04 |
+-----------------------+
1 row in set (0.00 sec)

SELECT DATE_ADD(CURDATE(), INTERVAL 2 MONTH);


+---------------------------------------------------------------+
| DATE_ADD(CURDATE(), INTERVAL 2 MONTH) |
+----------------------------------------------------------------+
| 2024-12-14 |
+----------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT NOW();


+--------------------------+
| NOW() |
+--------------------------+
| 2024-10-14 20:40:56 |
+--------------------------+
1 row in set (0.00 sec)

mysql> select curdate();


+-----------------+
| curdate() |
+---------------- +
| 2024-10-14 |
+-----------------+
1 row in set (0.00 sec)

36
mysql> select month(curdate());
+---------------------+
| month(curdate()) |
+---------------------+
| 10 |
+----------------------+
1 row in set (0.00 sec)

mysql> select current_timestamp from dual;


+-------------------------+
| current_timestamp |
+-------------------------+
| 2024-10-14 20:42:14 |
+--------------------------+
1 row in set (0.00 sec)

Result:
Aggregate and Built-in functions have been executed.

37
Experiment No:7 Date:23/09/24

Practice of SQL TCL Commands

AIM

Practice of SQL TCL commands like Rollback, Commit, Savepoint .

List of TCL (Transaction Control Language) commands:

COMMIT: Commits a Transaction.

ROLLBACK: Rollbacks a transaction in case of any error occurs.

SAVEPOINT: Sets a savepoint within a transaction.

COMMIT command

COMMIT command is used to permanently save any transaction into the database.

When we use any DML command like INSERT, UPDATE or DELETE, the changes
made by these commands are not permanent, until the current session is closed, the
changes made by these commands can be rolled back.

To avoid that, we use the COMMIT command to mark the changes as permanent.

Following is commit command's syntax,

COMMIT;

ROLLBACK command

38
This command restores the database to last commited state. It is also used with
SAVEPOINT command to jump to a savepoint in an ongoing transaction.

If we have used the UPDATE command to make some changes into the database, and
realise that those changes were not required, then we can use the ROLLBACK command
to rollback those changes, if they were not commited using the COMMIT command.

Following is rollback command's syntax,

ROLLBACK TO savepoint_name;

SAVEPOINT command

SAVEPOINT command is used to temporarily save a transaction so that you can rollback
to that point whenever required.

Following is savepoint command's syntax,

SAVEPOINT savepoint_name;

Using Savepoint and Rollback

Following is the table class,

Id Name

1 Abhi

2 Adam

4 Alex

INSERT INTO class VALUES(5, 'Rahul');

39
COMMIT;

start transaction;

UPDATE class SET name = 'Abhijit' WHERE id = '5';

SAVEPOINT A;

INSERT INTO class VALUES(6, 'Chris');

SAVEPOINT B;

INSERT INTO class VALUES(7, 'Bravo');

SAVEPOINT C;

SELECT * FROM class;

The resultant table will look like,

Id Name

1 Abhi

2 Adam

4 Alex

5 Abhijit

40
6 Chris

7 Bravo

ROLLBACK TO B;

SELECT * FROM class;

Id Name

1 Abhi

2 Adam

4 Alex

5 Abhijit

Result:
SQL TCL Commands have been executed.

41
Experiment No:8 Date:27/09/24

PL/SQL Programs

AIM
Implementation of various control structures like IF-THEN, IF-THEN-ELSE,
IF-THEN-ELSIF, CASE, WHILE using PL/SQL.

PL/SQL PROGRAMS

1. PL/SQL code to print Hello World.

begin
dbms_output.put_line('hello world');
end ;
/
output:
Statement processed.
hello world

2. PL/SQL code to add two numbers.

declare
var1 integer;
var2 integer;
var3 integer;
begin
var1:=5;
var2:=6;
var3:=var1+var2;
dbms_output.put_line(var3);
end ;
/
output:
Statement processed.
11

42
3. PL/SQL code to find reverse of a number.

declare
n number;
i number;
rev number:=0;
r number;
begin
n:=678;
while n>0
loop
r:=mod(n,10);
rev:=(rev*10)+r;
n:=trunc(n/10);
end loop;
dbms_output.put_line('reverse is:'||rev);
end;

Output:
Statement processed.
reverse is:876

4. PL/SQL code to find whether a number is prime or not.

declare
n number;
i number;
flag number;
begin
i:=2;
flag:=1;
n:=11;
for i in 2..n/2
loop
if mod(n,i)=0
then
flag:=0;

43
exit;
end if;
end loop;
if flag=1
then
dbms_output.put_line(n||' is prime');
else
dbms_output.put_line(n||' is not prime');
end if;
end;

output:
Statement processed.
11 is prime

5. PL/SQL code to find reverse of a String

declare
str1 varchar(50):='DATABASE';
str2 varchar(50);
len number;
i number;
begin
len:=length(str1);
for i in reverse 1..len
loop
str2:=str2||substr(str1,i,1);
end loop;
dbms_output.put_line('Reverse of string is:'||str2);
end ;
/

output:
Statement processed.
Reverse of string is:ESABATAD

44
6. PL/SQL code to find the largest of three numbers.

declare
a number:=10;
b number:=12;
c number:=5;
begin
dbms_output.put_line('a='||a||',b='||b||',c='||c);
if a>b and a>c
then
dbms_output.put_line(a||' is largest');
else
if b>a and b>c
then
dbms_output.put_line(b||' is largest');
else
dbms_output.put_line(c||' is largest');
end if;
end if;
end ;
/

output:
Statement processed.
a=10,b=12,c=5
12 is largest

7.PL/SQL code to use CASE statement to print a color based on the given code.

(Hint: R-Red, B-blue, G-Green, Y-Yellow)

declare

color varchar(2):='G';

begin

45
case color

when 'R' then dbms_output.put_line('Red');

when 'B' then dbms_output.put_line('Blue');

when 'G' then dbms_output.put_line('Green');

end case;

end ;

output:

Statement processed.

Green

8.PL/SQL code to use CASE statement to print the result based on grade.

declare
grade varchar(2):='B';
begin
case grade
when 'A' then dbms_output.put_line('Excelent');
when 'B' then dbms_output.put_line('Very Good');
when 'C' then dbms_output.put_line('Good');
when 'D' then dbms_output.put_line('Fair');
when 'F' then dbms_output.put_line('Poor');
else dbms_output.put_line('No Such Grade');
end case;
end ;
/

output:

46
Statement processed.
Very Good

Result:
PL/SQL Programs have been executed .

47
Experiment No:9 Date:27/09/24

PL/SQL Cursors and Exceptions

AIM

Creation of Cursors and PL/SQL blocks for exception handling.

Create an Employee table as given below.

ENAME SSN SALARY EXPERIENCE

Anil 400 12000 7

Rani 100 10000 5

Raja 200 11000 5

Anu 300 12000 6

1. Increment the salary of the employee with ssn=100, by Rs 2000, if his experience
>5years. Otherwise increment his salary by Rs 1000.

2.Increment the salary of the employees by 10% if his experience > 5years. Otherwise
increment his salary by Rs 500. Use Cursor.

3.From the above table retrieve the details of employee with ssn=200. Raise an exception
if such an employee does not exist.

DDL:

create table employee(ename varchar(50),ssn int primary key,salary float,experience int);


Output:
Table created
insert into employee values('Anil',400,12000,7);
1 row(s) inserted.
insert into employee values('Rani',100,10000,5);
1 row(s) inserted.

48
insert into employee values('Raja',200,11000,5);
1 row(s) inserted.
insert into employee values('Anu',300,12000,6);
1 row(s) inserted.

select * from employee;


Output:
Result Set 1

ENAME SSN SALARY EXPERIENCE


Rani 100 10000 5
Anil 400 12000 7
Raja 200 11000 5
Anu 300 12000 6

4 rows selected.

PL/SQL Programs:
1. Increment the salary of the employee with ssn=100, by Rs 2000, if his experience
>5years. Otherwise increment his salary by Rs 1000.

declare
exp employee.experience%type;
sal employee.salary%type;
begin
select experience,salary into exp,sal from employee where ssn=100;
if exp>5 then
sal:=sal+2000;
else
sal:=sal+1000;
end if;
update employee set salary=sal where employee.ssn=100;
end ;
/
Output:
Statement processed.

49
select * from employee where ssn=100;
Output:
Result Set 3

ENAME SSN SALARY EXPERIENCE


Rani 100 11000 5

2.Increment the salary of the employees by 10% if his experience > 5years.
Otherwise increment his salary by Rs 500. Use Cursor.

declare
exp employee.experience%type;
sal employee.salary%type;
ename employee.ename%type;
ssn employee.ssn%type;
cursor crs is select ename,ssn,experience,salary from employee for update of
salary;
begin
open crs;
loop
fetch crs into ename,ssn,exp,sal;
exit when crs%notfound;
if exp>5 then
sal:=sal+(sal*0.1);
else
sal:=sal+500;
end if;
update employee set salary=sal where current of crs;
dbms_output.put_line(ename||''||ssn||''||exp||''||sal||'');
end loop;
end ;
/
output:
Statement processed.
Rani100511500
Anil400713200
Raja200511500
Anu300613200

50
select * from employee;
output:
Result Set 4

ENAME SSN SALARY EXPERIENCE


Rani 100 11500 5
Anil 400 13200 7
Raja 200 11500 5
Anu 300 13200 6
4 rows selected.

3.From the above table retrieve the details of employee with ssn=200. Raise an
exception if such an employee does not exist.

declare
sn int;
begin
select ssn into sn from employee where ssn = 500;
exception
when no_data_found then
dbms_output.put_line('No such Employee Exits');
end ;
/

output:
Statement processed.
No such Employee Exits

Result:
PL/SQL Cursors and Exceptions have been executed.

51
Experiment No:10 Date:30/09/24

SQL Procedures and Functions

AIM

Creation of Procedures and Functions

1. Write a procedure to find out the name of the employee having maximum salary.

2. Write a procedure to accept the department no and print the details of its manager.

3. Write a function to get the details of all employees working on proj1.

4. Create a procedure to give Rs.1000 hike in the salary of all the employees who work
in Research department. Update the table accordingly.

5. Create a trigger to update the total salary of a department when a new employee is
hired.

6. The company has a policy that the minimum salary for an employee is 10000.
Create a trigger to check if the salary entered while inserting a tuple is greater than
or equal to 10000. Else generate an error message with the text “salary should be
greater than or equal to 10000”

Query:

1. Write a procedure to find out the name of the employee having maximum salary.

DELIMITER $$
mysql> CREATE PROCEDURE GetMaxSalaryEmployee()
-> BEGIN

52
-> SELECT FNAME,LNAME,SALARY FROM EMPLOYEE WHERE
SALARY=(SELECT MAX(SALARY) FROM EMPLOYEE);
-> END $$
Query OK, 0 rows affected (0.01 sec)
DELIMITER ;
CALL GetMaxSalaryEmployee();
+-----------+-----------+------------+
| FNAME | LNAME | SALARY |
+-----------+-----------+------------+
| Rani | Patel | 62000 |
+-----------+----------+------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

2. Write a procedure to accept the department no and print the details of its
manager.

mysql> DELIMITER //
mysql> CREATE PROCEDURE GetManagerDetailsByDept(IN dept_no INT)
-> BEGIN
-> SELECT E.FNAME,E.LNAME,E.SSN,E.SALARY,E.ADDRESS FROM
EMPLOYEE AS E JOIN DEPARTMENT AS D ON E.SSN=D.MGRSSN
-> WHERE D.DNUMBER=dept_no;
-> END //
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;

CALL GetManagerDetailsByDept(4);
+-----------+-----------+--------------+-------------+---------------------+
| FNAME | LNAME | SSN | SALARY | ADDRESS |
+-----------+-----------+--------------+-------------+---------------------+
| Rani | Patel | 555555555 | 62000 | T Nagar, Chennai |
+-----------+-----------+--------------+------------+-----------------------+

53
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

3. Write a function to get the details of all employees working on proj1.

DELIMITER //
mysql> CREATE FUNCTION GETEMPDETAILS(PROJ INT)
-> RETURNS VARCHAR(255) DETERMINISTIC
-> BEGIN
-> DECLARE RESULT VARCHAR(255);
-> SELECT GROUP_CONCAT(E.FNAME,E.LNAME ORDER BY E.FNAME
SEPARATOR '\n')
-> INTO
-> RESULT FROM EMPLOYEE AS E,WORKS_ON AS W WHERE
E.SSN=W.ESSN AND PNO=PROJ;
-> RETURN RESULT;
-> END //
Query OK, 0 rows affected (0.00 sec)

SELECT GETPROJEMPDETAIL(1);
+----------------------------------------+
| GETPROJEMPDETAIL(1) |
+----------------------------------------+
| AnitaVerma,JohnDoe,SanjayRaj |
+---------------------------------------+

CREATE FUNCTION GETEMPDETAIL(PROJ INT)


-> RETURNS VARCHAR(255) DETERMINISTIC
-> BEGIN
-> DECLARE RESULT VARCHAR(255);
-> SELECT GROUP_CONCAT('name: ',E.FNAME,'\tlastName :',E.LNAME ORDER
BY E.FNAME SEPARATOR '\n')
-> INTO
-> RESULT FROM EMPLOYEE AS E,WORKS_ON AS W WHERE
E.SSN=W.ESSN AND PNO=PROJ;
-> RETURN RESULT;

54
-> END //
Query OK, 0 rows affected (0.01 sec)

mysql> select GETEMPDETAIL(1)//


+---------------------------------------------------------------------------------+
| GETEMPDETAIL(1) |
+---------------------------------------------------------------------------------+
| name: Anita lastName :Verma |
|name: John lastName :Doe |
|name: Sanjay lastName :Raj |
+---------------------------------------------------------------------------------+
1 row in set (0.00 sec)

4. Create a procedure to give Rs.1000 hike in the salary of all the employees who
work in Research department. Update the table accordingly.

DELIMITER //
mysql> CREATE PROCEDURE UPDATESALARY()
-> BEGIN
-> UPDATE EMPLOYEE AS E JOIN DEPARTMENT AS D ON
E.DNO=D.DNUMBER SET SALARY=SALARY+1000 WHERE
DNAME="Research";
-> END //
Query OK, 0 rows affected (0.00 sec)

DELIMITER ;
mysql> SELECT SSN,SALARY FROM EMPLOYEE,DEPARTMENT WHERE
DNO=DNUMBER and DNAME="Research";

55
+------------+------------+
| SSN | SALARY |
+------------+------------+
| 111111111 | 50000 |
+-------------+-----------+
1 row in set (0.00 sec)

mysql> CALL UPDATESALARY();


Query OK, 1 row affected (0.00 sec)

mysql> SELECT SSN,SALARY FROM EMPLOYEE,DEPARTMENT WHERE


DNO=DNUMBER and DNAME="Research";
+---------------+------------+
| SSN | SALARY |
+--------------+------------+
| 111111111 | 51000 |
+--------------+------------+
1 row in set (0.00 sec)

5. Create a trigger to update the total salary of a department when a new employee

is hired.

ALTER TABLE DEPARTMENT ADD COLUMN TOTAL_SALARY FLOAT


DEFAULT 0.0;
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0

UPDATE DEPARTMENT AS D SET TOTAL_SALARY=(SELECT SUM(E.SALARY)


FROM EMPLOYEE AS E WHERE E.DNO=D.DNUMBER);
Query OK, 4 rows affected (0.00 sec)

56
Rows matched: 4 Changed: 4 Warnings: 0

mysql> SELECT * FROM DEPARTMENT;


+-------------------+---------------+----------------+-------------------- --+-----------------------+
| DNAME | DNUMBER | MGRSSN | MGRSTARTDATE | TOTAL_SALARY |
+-------------------+---------------+---------------+------------------------+-----------------------+
| Research | 1 | 111111111 | 2010-01-01 | 51000 |
| Administration | 2 | 444444444 | 2011-02-15 | 107000 |
| IT | 4 | 555555555 | 2013-04-20 | 62000 |
| HR | 5 | 666666666 | 2014-05-25 | 95000 |
+------------------+----------------+----------------+------------------------+----------------------+
4 rows in set (0.00 sec)

mysql> DELIMITER //
mysql> CREATE TRIGGER UpdateTotalSalary
-> AFTER INSERT ON EMPLOYEE
-> FOR EACH ROW
-> BEGIN
-> UPDATE DEPARTMENT SET
TOTAL_SALARY=TOTAL_SALARY+NEW.SALARY
-> WHERE DNUMBER=NEW.DNO;
-> END //
Query OK, 0 rows affected (0.01 sec)

mysql> DELIMITER ;
mysql> INSERT INTO EMPLOYEE
VALUES("Aarav","K","Patel",999999999,"1995-07-10","MG
Road,Bangalore","M",60000,NULL,2);
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM DEPARTMENT;

57
mysql> SELECT * FROM DEPARTMENT;
+-------------------+---------------+----------------+-------------------- --+-----------------------+
| DNAME | DNUMBER | MGRSSN | MGRSTARTDATE | TOTAL_SALARY |
+-------------------+---------------+---------------+------------------------+-----------------------+
| Research | 1 | 111111111 | 2010-01-01 | 51000 |
| Administration | 2 | 444444444 | 2011-02-15 | 167000 |
| IT | 4 | 555555555 | 2013-04-20 | 62000 |
| HR | 5 | 666666666 | 2014-05-25 | 95000 |
+------------------+----------------+----------------+------------------------+----------------------+
4 rows in set (0.00 sec)

6. The company has a policy that the minimum salary for an employee is 10000.
Create a trigger to check if the salary entered while inserting a tuple is greater
than or equal to 10000. Else generate an error message with the text “salary
should be greater than or equal to 10000”

CREATE TRIGGER CheckMinSalary


-> BEFORE INSERT ON EMPLOYEE
-> FOR EACH ROW
-> BEGIN
-> IF NEW.SALARY<10000 THEN
-> SIGNAL SQLSTATE '45000'
-> SET MESSAGE_TEXT = "SALARY SHOULD BE GRATER THAN OR EQUAL
TO 10000!";
-> END IF;
-> END //
Query OK, 0 rows affected (0.01 sec)

DELIMITER ;
mysql> INSERT INTO EMPLOYEE
VALUES("Aarav","M","Singh",222222222,"1995-07-10","MG
Road,Bangalore","M",9000,NULL,1);
ERROR 1644 (45000): SALARY SHOULD BE GRATER THAN OR EQUAL TO
10000!

58
mysql> INSERT INTO EMPLOYEE
VALUES("Aarav","M","Singh",222222222,"1995-07-10","MG
Road,Bangalore","M",49000,NULL,1);
Query OK, 1 row affected (0.00 sec)

Result:
SQL Procedures and Functions have been executed.

59
Experiment No:11 Date:14/10/24

MongoDB Queries

AIM
Familiarization of NoSQL Databases and CRUD operations.

We have to input some datas first in order to do queries.


> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
mydb 0.000GB
>
> use mydb_57
switched to db mydb_57
> db
mydb_57
>
db.createCollection('inventory')
{ "ok" : 1 }
db.inventory.insertMany([
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);

Query:
1. Add a new field ‘count’ whose value is 10 to the document where the item =
“journal”.

db.inventory.update(
{ item: "journal" },
{ $set: { count: 10 } }
)

60
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

db.inventory.find({})

{
"_id" : ObjectId("6560ace2e441817748969bc2"),
"item" : "journal",
"qty" : 25,
"size" : { "h" : 14, "w" : 21, "uom" : "cm" },
"status" : "A",
"count" : 10
}
{
"_id" : ObjectId("6560ace2e441817748969bc3"),
"item" : "notebook",
"qty" : 50,
"size" : { "h" : 8.5, "w" : 11, "uom" : "in" },
"status" : "A"
}
{
"_id" : ObjectId("6560ace2e441817748969bc4"),
"item" : "paper",
"qty" : 100,
"size" : { "h" : 8.5, "w" : 11, "uom" : "in" },
"status" : "D"
}
{
"_id" : ObjectId("6560ace2e441817748969bc5"),
"item" : "planner",
"qty" : 75,
"size" : { "h" : 22.85, "w" : 30, "uom" : "cm" },
"status" : "D"
}
{
"_id" : ObjectId("6560ace2e441817748969bc6"),
"item" : "postcard",

61
"qty" : 45,
"size" : { "h" : 10, "w" : 15.25, "uom" : "cm" },
"status" : "A"
}

2. Increment quantity by 10 where item = “notebook”.

db.inventory.update(
{ item: "notebook" },
{ $inc: { qty: 10 } }
)

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

db.inventory.find({})

{
"_id" : ObjectId("6560ace2e441817748969bc2"),
"item" : "journal",
"qty" : 25,
"size" : { "h" : 14, "w" : 21, "uom" : "cm" },
"status" : "A",
"count" : 10
}
{
"_id" : ObjectId("6560ace2e441817748969bc3"),
"item" : "notebook",
"qty" : 60,
"size" : { "h" : 8.5, "w" : 11, "uom" : "in" },
"status" : "A"
}
{
"_id" : ObjectId("6560ace2e441817748969bc4"),
"item" : "paper",
"qty" : 100,
"size" : { "h" : 8.5, "w" : 11, "uom" : "in" },
"status" : "D"

62
}
{
"_id" : ObjectId("6560ace2e441817748969bc5"),
"item" : "planner",
"qty" : 75,
"size" : { "h" : 22.85, "w" : 30, "uom" : "cm" },
"status" : "D"
}
{
"_id" : ObjectId("6560ace2e441817748969bc6"),
"item" : "postcard",
"qty" : 45,
"size" : { "h" : 10, "w" : 15.25, "uom" : "cm" },
"status" : "A"
}

3. For the third document , decrement the quantity by 15 and set status to “C”.

db.inventory.updateOne(
{ item: "paper" },
{ $inc: { qty: -15 }, $set: { status: "C" } }
)

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

db.inventory.find({})

{
"_id" : ObjectId("6560ace2e441817748969bc2"),
"item" : "journal",
"qty" : 25,
"size" : { "h" : 14, "w" : 21, "uom" : "cm" },
"status" : "A",
"count" : 10
}
{
"_id" : ObjectId("6560ace2e441817748969bc3"),

63
"item" : "notebook",
"qty" : 60,
"size" : { "h" : 8.5, "w" : 11, "uom" : "in" },
"status" : "A"
}
{
"_id" : ObjectId("6560ace2e441817748969bc4"),
"item" : "paper",
"qty" : 85,
"size" : { "h" : 8.5, "w" : 11, "uom" : "in" },
"status" : "C"
}
{
"_id" : ObjectId("6560ace2e441817748969bc5"),
"item" : "planner",
"qty" : 75,
"size" : { "h" : 22.85, "w" : 30, "uom" : "cm" },
"status" : "D"
}
{
"_id" : ObjectId("6560ace2e441817748969bc6"),
"item" : "postcard",
"qty" : 45,
"size" : { "h" : 10, "w" : 15.25, "uom" : "cm" },
"status" : "A"
}

4. Delete size field where item = “paper”.

db.inventory.updateOne(
{ item: "paper" },
{ $unset: { size: "" } }
)

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

db.inventory.find({})

64
{
"_id" : ObjectId("6560ace2e441817748969bc2"),
"item" : "journal",
"qty" : 25,
"size" : { "h" : 14, "w" : 21, "uom" : "cm" },
"status" : "A",
"count" : 10
}
{
"_id" : ObjectId("6560ace2e441817748969bc3"),
"item" : "notebook",
"qty" : 60,
"size" : { "h" : 8.5, "w" : 11, "uom" : "in" },
"status" : "A"
}
{
"_id" : ObjectId("6560ace2e441817748969bc4"),
"item" : "paper",
"qty" : 85,
"status" : "C"
}
{
"_id" : ObjectId("6560ace2e441817748969bc5"),
"item" : "planner",
"qty" : 75,
"size" : { "h" : 22.85, "w" : 30, "uom" : "cm" },
"status" : "D"
}
{
"_id" : ObjectId("6560ace2e441817748969bc6"),
"item" : "postcard",
"qty" : 45,
"size" : { "h" : 10, "w" : 15.25, "uom" : "cm" },
"status" : "A"
}

65
5. Delete the documents where status = “A”.

db.inventory.remove({ status: "A" })

WriteResult({ "nRemoved" : 3 })

db.inventory.find({})

{
"_id" : ObjectId("6560ace2e441817748969bc4"),
"item" : "paper",
"qty" : 85,
"status" : "C"
}
{
"_id" : ObjectId("6560ace2e441817748969bc5"),
"item" : "planner",
"qty" : 75,
"size" : { "h" : 22.85, "w" : 30, "uom" : "cm" },
"status" : "D"
}

6. Find the number of documents in the inventory document .

> db.inventory.count()
2

7. Drop inventory collection .

> db.inventory.drop()
True

8. Drop the Database

db.dropDatabase()

66
{ "dropped" : "mydb_57", "ok" : 1 }

show dbs

admin 0.000GB
config 0.000GB
local 0.000GB
mydb 0.000GB

Result:
NoSQL Database has been created and CRUD operations are executed .

67
Experiment No:12 Date:4/11/24

DBMS PROJECT

Aim:
The aim of this project is to design and implement a comprehensive railway management
system that manages railway operations efficiently, enhances passenger experience, and
secures ticketing processes.

Objective:
This project aims to create a digital platform for railway booking, passenger
management, and scheduling, reducing manual intervention and making railway services
more accessible to users.

Introduction:
Railways serve as a backbone for mass transportation. Managing such a system requires a
structured platform that simplifies ticket booking, passenger management, and
scheduling. This project focuses on developing a railway management system with
essential features like user login, signup, and train schedule viewing, enabling users to
access information and services conveniently.

Software Used:

● Backend: MySQL for database management, ensuring efficient handling of


relational data. PHP powers server-side scripting for database interactions and user
management.
● Frontend: HTML, CSS, and JavaScript are used to create a responsive,
easy-to-navigate interface.

Design (Frontend and Backend):


The design includes:

● Frontend: A user-friendly interface with login and signup options, pages for train
schedule viewing, ticket booking, a streamlined booking process and cancel
tickets.

68
● Backend: A robust relational database to store user data, ticket information, and
train schedules. Database relations, such as foreign keys, maintain data
consistency and integrity.

Methodology:

1. Requirement Analysis: Defining the system's core functionalities, such as user


registration, train schedule viewing, ticket booking and cancel tickets.
2. Database Design: Developing ER diagrams and implementing relational tables to
manage passenger, schedule, and booking data.
3. System Development: Creating frontend interfaces and backend scripts to support
user interactions and database operations.

SCREENSHOTS:
DATABSE CONNECTION:

69
Homepage:

Login And SignUp Page:

70
Booking Pages:

71
Train Schedule:

72
Cancel Ticket:

Database:
railway_system:
user(username, password, email, mobile_number, gender, age, name)
train(train_no, train_name, seat_avail, class)
passanger(pno, p_name, p_age, p_gender, seat_no, ticket_no)
station(station_no, source, destination, fare, arrival_time, depart_time, duration, train_no)
ticket(ticket_no, status, date, phno, email, train_no, station_no, username)

Relationships and Constraints:

● passanger.ticket_no references ticket(ticket_no) with ON DELETE CASCADE.

73
● station.train_no references train(train_no) with ON DELETE CASCADE.
● ticket.train_no references train(train_no).
● ticket.station_no references station(station_no).
● ticket.username references user(username) with ON DELETE CASCADE.

Conclusion:
The Railway Management System database project offers an effective solution for
managing railway operations by integrating user accounts, train schedules, ticketing, and
passenger details into a cohesive relational database. This structure ensures data integrity and
improves user experience, facilitating seamless interactions for user registration, ticket booking,
and train scheduling. Overall, the project provides a solid foundation for a scalable and efficient
railway management system, ready to adapt to future needs and enhancements.

Result:
Database connectivity have been performed.

74

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy