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

Rdbms Lab Report(d)090

The document details a lab record report for a student named Dharani Shree K, covering various database design and manipulation tasks. It includes the creation of multiple tables, application of DDL and DML commands, and the implementation of constraints in different database scenarios such as a College Database, Library Database, and Employee Management. The report outlines SQL commands for table creation, data insertion, updates, and queries to retrieve specific information based on given conditions.
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)
19 views

Rdbms Lab Report(d)090

The document details a lab record report for a student named Dharani Shree K, covering various database design and manipulation tasks. It includes the creation of multiple tables, application of DDL and DML commands, and the implementation of constraints in different database scenarios such as a College Database, Library Database, and Employee Management. The report outlines SQL commands for table creation, data insertion, updates, and queries to retrieve specific information based on given conditions.
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/ 55

LAB RECORD REPORT

NAME : DHARANI SHREE K


USN : SCA24MCA0009
CLASS : MCA ‘A’ SEC
Program No:1
------------------------------------------------------------------------------------------------------
Design any database with atleast 3 entities and relationship between then. Apply DDL
commands. Draw suitable ER Diagram suitable for the system
1. College Database
2. Library Database
3. Company Database
Or any other
----------------------------------------------------------------------------------------------------

1. Create table following tables with the attributes mentioned below STUDENT (USN,SNAME,
ADDRESS ,PHONE) SEMSEC (SSID , SEM ,SEC ) , IAMARKS (USN ,SUBID,SSID
,TEST1,TEST2,TEST3 ,FINALIA) SUBJECT (SUBID,TITLE,SEM,CREDIT) CLASS
(USN,SSID

CREATE DATABASE CollegeDB;


USE CollegeDB;

CREATE TABLE STUDENT (


USN VARCHAR(10) PRIMARY KEY,
SNAME VARCHAR(50),
ADDRESS VARCHAR(100),
PHONE VARCHAR(15)
);

CREATE TABLE SEMSEC (


SSID INT PRIMARY KEY,
SEM INT,
SEC CHAR(1)
);

CREATE TABLE IAMARKS (


USN VARCHAR(10),
SUBID VARCHAR(10),
SSID INT,
TEST1 INT,
TEST2 INT,
TEST3 INT,
FINALIA INT,
PRIMARY KEY (USN, SUBID),
FOREIGN KEY (USN) REFERENCES STUDENT(USN),
FOREIGN KEY (SSID) REFERENCES SEMSEC(SSID)
);

CREATE TABLE SUBJECT (


SUBID VARCHAR(10) PRIMARY KEY,
TITLE VARCHAR(50),
SEM INT,
CREDIT INT
);

CREATE TABLE CLASS (


USN VARCHAR(10),
SSID INT,
PRIMARY KEY (USN, SSID),
FOREIGN KEY (USN) REFERENCES STUDENT(USN),
FOREIGN KEY (SSID) REFERENCES SEMSEC(SSID)
);

SHOW TABLES;

2. Add new column with name GENDER with datatype varchar and size 1 in table STUDENT
ALTER TABLE STUDENT ADD GENDER VARCHAR(1);
SELECT * FROM STUDENT;

3. Add two new columns FEES as integer and DOB as varchar in table STUDENT

ALTER TABLE STUDENT ADD FEES INT, ADD DOB VARCHAR(10);


SELECT * FROM STUDENT;

4. Change the data type of column DOB to Date type in student table

ALTER TABLE STUDENT MODIFY COLUMN DOB DATE;


SELECT * FROM STUDENT

5. Change the name of column DOB to Dateofbirth in student table.


ALTER TABLE STUDENT RENAME COLUMN DOB TO DateOfBirth;
SELECT * FROM STUDENT;

6. Change the table name from STUDENT to NEWSTUDENT.

RENAME TABLE STUDENT TO NEWSTUDENT;


SELECT * FROM NEWSTUDENT;
SHOW TABLES;

7. Delete the column PHONE from student table

ALTER TABLE NEWSTUDENT DROP COLUMN PHONE;


SELECT * FROM NEWSTUDENT;

8. Delete the table NEWSTUDENT


The NEWSTUDENT table (previously STUDENT) has a primary key USN.

This USN is referenced as a foreign key in two tables:

1. IAMARKS → FOREIGN KEY (USN) REFERENCES STUDENT(USN)


2. CLASS → FOREIGN KEY (USN) REFERENCES STUDENT(USN)

SELECT TABLE_NAME, CONSTRAINT_NAME


FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME = 'NEWSTUDENT';

ALTER TABLE IAMARKS DROP FOREIGN KEY iamarks_ibfk_1;


ALTER TABLE CLASS DROP FOREIGN KEY class_ibfk_1;

DROP TABLE NEWSTUDENT;


SHOW TABLES;

Program No:2
------------------------------------------------------------------------------------------------------
Title: Design and implement a database and apply at least 10 different DML queries for the
following task. For a given input string display only those records which match the given pattern
or a phrase in the search string. Make use of wild characters and LIKE operator for the same.
Make use of Boolean and arithmetic operators wherever necessary.
-------------------------------------------------------------------------------------------------------

create database program2;


use program2;

1.Create table emp_chk with attributes EMP_ID varchar(10), ENAME varchar (15), JOB varchar
(15), HIREDATE DATE, SAL varchar(10), COMM varchar(10), DEPT_NO varchar(10).

CREATE TABLE emp_chk(EMP_ID varchar(10), ENAME varchar(15), JOB varchar(15),


HIREDATE DATE, SAL varchar(10), COMM varchar(10), DEPT_NO varchar(10));

2.Insert the records into the emp_chk table and display all the records of the emp_chk table.

INSERT INTO emp_chk(EMP_ID,ENAME,JOB,HIREDATE,SAL,COMM,DEPT_NO)


values(01,"ARYA","SUPERVISOR",'2000-01-12',1000,5,2);
SELECT * FROM emp_chk;

3.Create another table emp with all the attributes of emp_chk table and insert all the records of
emp_chk table into emp table at a time.

CREATE TABLE emp LIKE emp_chk;


SELECT * FROM emp;

INSERT INTO emp SELECT * FROM emp_chk;


(Values of original table gets inserted to a new created table.)
(Multiple values insertion to the database.)
INSERT INTO emp(EMP_ID , ENAME, JOB, HIREDATE , SAL , COMM , DEPT_NO )
values
(0002, 'Aditya','Supervisor','2000-10-12',2000,6,5),
(0003, 'Srihanth','Worker','2012-02-02',5000,8,2),
(0004, 'Sathya','Emp1','2019-10-12',1000,1,8);

4.Display all the information of emp table whose salary is greater than 2000

SELECT * FROM emp WHERE SAL>2000;

5.Display distinct salary from emp table.

SELECT DISTINCT SAL FROM emp;

6.Display the record of emp table in ascending order of hire date.

SELECT * FROM emp ORDER BY HIREDATE asc;


7.Display the record of emp table in decreasing order of hire date.

SELECT * FROM emp ORDER BY HIREDATE desc;

8.Update the salary of employee to 5000 whose employee id is 5.


ALTER TABLE emp
ADD PRIMARY KEY (EMP_ID);
//Above statements are required if we get error saying:
[Code: 1175. You are using safe update mode and you tried to update a table without a
WHERE that uses a KEY column. To disable safe mode, toggle the option in Preferences
-> SQL Editor and reconnect.]

ALTER TABLE emp


ADD PRIMARY KEY(EMP_ID);
UPDATE emp set SAL = 5000 where EMP_ID = 5;

/*OR*/

SET SQL_SAFE_UPDATES = 0;
update emp set SAL = 3000 where EMP_ID = 5;
SET SQL_SAFE_UPDATES = 1;
SELECT * FROM emp;

9.Delete the record of employee whose employee id is 2.


SET SQL_SAFE_UPDATES = 0;
delete from emp where EMP_ID = 2;
SELECT * FROM emp;

10.Display the salary of employee whose salary is in the range of 2000 to 5000.

SELECT * FROM emp WHERE SAL BETWEEN 2000 AND 5000;

11.Display the records of employee whose jobs are ‘Manager’,’Supervisor’ and ‘Worker’.

SELECT * FROM emp WHERE JOB IN ('Manager', 'Supervisor', 'Worker');

12.Display name of employee whose name starts with A.

SELECT * FROM emp WHERE ENAME LIKE 'A%';


Display name of employee whose name starts with A or S.

SELECT * FROM emp WHERE ENAME LIKE 'A%' or ENAME LIKE 'S%';

13.Display the name of employees whose name does not start with A.

SELECT * FROM emp WHERE ENAME NOT LIKE 'A%';

14.Write a SQL statement to increase the salary of employees under the department 2, 5 and 8
according to the company rules that, salary will be increased by 25% for the department 2, 15%
for department 5 and 10% for the department 8 and the rest of the departments will remain same.

UPDATE emp SET sal= CASE dept_no


WHEN 2 THEN sal+(sal*.25)
WHEN 5 THEN sal+(sal*.15)
WHEN 8 THEN sal+(sal*.10)
ELSE sal
END
WHERE dept_no IN (2,5,2,8);
SELECT * FROM emp;
Program No:3 – On Constraints ---------------------------------------------------------------------------
------------------------------------
1. Consider the following schema for a Library Database:

BOOK (Book_id, Title, Publisher_Name, Pub_Year)


BOOK_AUTHORS (Book_id, Author_Name)
PUBLISHER (Name, Address, Phone)
BOOK_COPIES (Book_id, Branch_id, No-of_Copies)
BOOK_LENDING (Book_id, Branch_id, Card_No, Date_Out, Due_Date)
LIBRARY_BRANCH (Branch_id, Branch_Name, Address)

---------------------------------------------------------------------------------------------------------------
Table Creation -
CREATE TABLE PUBLISHER (PUBL_NAME VARCHAR (20) PRIMARY KEY,
PHONE BIGINT,
ADDRESS VARCHAR (20));

CREATE TABLE BOOK (BOOK_ID INTEGER NOT NULL PRIMARY KEY,


TITLE VARCHAR (20),
PUB_YEAR VARCHAR (20),
PUBL_NAME varchar(20),
FOREIGN KEY (PUBL_NAME) REFERENCES PUBLISHER (PUBL_NAME) ON DELETE
CASCADE);

CREATE TABLE BOOK_AUTHORS (AUTHOR_NAME VARCHAR (20),


BOOK_ID int,
FOREIGN KEY (BOOK_ID) REFERENCES BOOK (BOOK_ID) ON
DELETE
CASCADE, PRIMARY KEY (BOOK_ID, AUTHOR_NAME));

CREATE TABLE LIBRARY_BRANCH (BRANCH_ID INTEGER PRIMARY KEY,


BRANCH_NAME VARCHAR (50),
ADDRESS VARCHAR (50));

CREATE TABLE BOOK_COPIES (NO_OF_COPIES INTEGER,


Book_id int,
branch_id int,
FOREIGN KEY (BOOK_ID) REFERENCES BOOK (BOOK_ID) ON DELETE CASCADE,
FOREIGN KEY (BRANCH_ID) REFERENCES LIBRARY_BRANCH (BRANCH_ID) ON
DELETE
CASCADE, PRIMARY KEY (BOOK_ID, BRANCH_ID));
CREATE TABLE CARD (CARD_NO INTEGER PRIMARY KEY);
CREATE TABLE BOOK_LENDING (DATE_OUT DATE, DUE_DATE DATE,
Book_id int,
Branch_id int,
card_no int,
FOREIGN KEY (BOOK_ID) REFERENCES BOOK (BOOK_ID) ON DELETE CASCADE,
FOREIGN KEY (BRANCH_ID) REFERENCES LIBRARY_BRANCH (BRANCH_ID) ON
DELETE CASCADE, FOREIGN KEY (CARD_NO) REFERENCES CARD (CARD_NO) ON
DELETE CASCADE, PRIMARY KEY (BOOK_ID, BRANCH_ID, CARD_NO));
Relational Schema -

Insertion of Values to Tables:

INSERT INTO PUBLISHER VALUES ('MCGRAW-HILL', 9989076587, 'BANGALORE');


INSERT INTO PUBLISHER VALUES ('PEARSON', 9889076565, 'NEWDELHI');
INSERT INTO PUBLISHER VALUES ('Jaico', 7455679345, 'HYDERABAD');
INSERT INTO PUBLISHER VALUES ('LIVRE', 8970862340, 'CHENNAI');
INSERT INTO PUBLISHER VALUES ('PLANETA', 7756120238, 'BANGALORE');

INSERT INTO BOOK VALUES (1, 'DBMS', '2017-01-18', 'MCGRAW-HILL');


INSERT INTO BOOK VALUES (2, 'ADBMS', '2016-06-16', 'MCGRAW-HILL');
INSERT INTO BOOK VALUES (3, 'CN', '2016-09-26', 'PEARSON');
INSERT INTO BOOK VALUES (4, 'CG', '2015-05-18', 'PLANETA');
INSERT INTO BOOK VALUES (5, 'OS', '2016-05-09', 'PEARSON');

INSERT INTO BOOK_AUTHORS VALUES ('NAVATHE', 1);


INSERT INTO BOOK_AUTHORS VALUES ('NAVATHE', 2);
INSERT INTO BOOK_AUTHORS VALUES ('TANENBAUM', 3);
INSERT INTO BOOK_AUTHORS VALUES ('EDWARD ANGEL', 4);
INSERT INTO BOOK_AUTHORS VALUES ('GALVIN', 5);

INSERT INTO LIBRARY_BRANCH VALUES (10, 'Branch1', 'BANGALORE');


INSERT INTO LIBRARY_BRANCH VALUES (11, 'Branch2', 'BANGALORE');
INSERT INTO LIBRARY_BRANCH VALUES (12, 'Branch3', 'BANGALORE');
INSERT INTO LIBRARY_BRANCH VALUES (13, 'Branch4', 'MANGALORE');
INSERT INTO LIBRARY_BRANCH VALUES (14, 'Branch5', 'MYSORE');

INSERT INTO BOOK_COPIES VALUES (10, 1, 10);


INSERT INTO BOOK_COPIES VALUES (5, 1, 11);
INSERT INTO BOOK_COPIES VALUES (2, 2, 12);
INSERT INTO BOOK_COPIES VALUES (5, 2, 13);
INSERT INTO BOOK_COPIES VALUES (7, 3, 14);
INSERT INTO BOOK_COPIES VALUES (1, 5, 10);
INSERT INTO BOOK_COPIES VALUES (3, 4, 11);

INSERT INTO CARD VALUES (100);


INSERT INTO CARD VALUES (101);
INSERT INTO CARD VALUES (102);
INSERT INTO CARD VALUES (103);
INSERT INTO CARD VALUES (104);

INSERT INTO BOOK_LENDING VALUES ('2017-01-21', '2017-06-21', 1, 10, 101);


INSERT INTO BOOK_LENDING VALUES ('2017-02-19', '2017-07-19', 3, 14, 101);
INSERT INTO BOOK_LENDING VALUES ('2017-02-26', '2017-07-26', 2, 13, 101);
INSERT INTO BOOK_LENDING VALUES ('2017-03-15', '2017-09-15', 4, 11, 101);
INSERT INTO BOOK_LENDING VALUES ('2017-04-12', '2017-10-12', 1, 11, 104);
Write SQL queries to -

1. Retrieve details of all books in the library – id, title, name of publisher, authors, number of
copies in each branch, etc.

SELECT B.BOOK_ID, B.TITLE, B.PUBL_NAME, A.AUTHOR_NAME,


C.NO_OF_COPIES, L.BRANCH_ID
FROM BOOK B, BOOK_AUTHORS A, BOOK_COPIES C, LIBRARY_BRANCH L
WHERE B.BOOK_ID=A.BOOK_ID
AND B.BOOK_ID=C.BOOK_ID
AND L.BRANCH_ID=C.BRANCH_ID;

2. Get the particulars of borrowers who have borrowed more than 3 books, but from Jan 2017 to
Jun 2017.

SELECT CARD_NO
FROM BOOK_LENDING
WHERE DATE_OUT BETWEEN '2017-01-21' AND '2017-09-15'
GROUP BY CARD_NO
HAVING COUNT(*)>3;
SELECT CARD_NO
FROM BOOK_LENDING
WHERE DATE_OUT BETWEEN '2017-01-21' AND '2017-09-15'
GROUP BY CARD_NO
HAVING COUNT(*)>3;

3. Delete a book in BOOK table. Update the contents of other tables to reflect this data
manipulation operation.

DELETE FROM BOOK


WHERE BOOK_ID=3;
SELECT * FROM BOOK;

4. Partition the BOOK table based on year of publication. Demonstrate its working with a simple
query.

CREATE VIEW V_PUBLICATION AS SELECT PUB_YEAR FROM BOOK;


SELECT * FROM V_PUBLICATION;
5. Create a view of all books and its number of copies that are currently available in the library.

CREATE VIEW V_BOOKS AS


SELECT B.BOOK_ID, B.TITLE, C.NO_OF_COPIES
FROM BOOK B, BOOK_COPIES C, LIBRARY_BRANCH L
WHERE B.BOOK_ID=C.BOOK_ID
AND C.BRANCH_ID=L.BRANCH_ID;

SELECT * FROM V_BOOKS;

6. List the book id, title ,publisher name, author name along with total number of copies of each
textbook and sort the records in the descending order of book_id.
SELECT B.BOOK_ID, B.TITLE, B.PUBL_NAME, A.AUTHOR_NAME,
SUM(C.NO_OF_COPIES) AS Total_Copies
FROM BOOK B
JOIN BOOK_AUTHORS A ON B.BOOK_ID = A.BOOK_ID
JOIN BOOK_COPIES C ON B.BOOK_ID = C.BOOK_ID
JOIN LIBRARY_BRANCH L ON C.BRANCH_ID = L.BRANCH_ID
GROUP BY B.BOOK_ID, B.TITLE, B.PUBL_NAME, A.AUTHOR_NAME
ORDER BY B.BOOK_ID DESC

7. List the book id, title, publisher name, along with total number of copies of each textbook
where number of copies is greater than 2 and sort the records in the ascending order of book_id.

SELECT B.BOOK_ID, B.TITLE, B.PUBL_NAME, A.AUTHOR_NAME,


SUM(C.NO_OF_COPIES) AS total_copies
FROM BOOK B
JOIN BOOK_AUTHORS A ON B.BOOK_ID = A.BOOK_ID
JOIN BOOK_COPIES C ON B.BOOK_ID = C.BOOK_ID
JOIN LIBRARY_BRANCH L ON L.BRANCH_ID = C.BRANCH_ID
GROUP BY B.BOOK_ID, B.TITLE, B.PUBL_NAME, A.AUTHOR_NAME
HAVING SUM(C.NO_OF_COPIES) > 2
ORDER BY B.BOOK_ID;
8. Retrieve the book id along with date of publication details of books which are published in
2016.

SELECT BOOK_ID,PUB_YEAR FROM BOOK WHERE PUB_YEAR LIKE '2016%';

9. Create / Alter table by ADD/ DROP CONSTRAINT – like NOT NULL, Unique, CHECK,
Primary Key, INDEX, AUTO INCREMENT, Foreign Key, DEFAULT
CREATE INDEX idx_BOOKS ON BOOK_AUTHORS (AUTHOR_NAME);
SHOW INDEXES FROM BOOK_AUTHORS;

ALTER TABLE BOOK_AUTHORS ADD CONSTRAINT Author_name_id_key UNIQUE


(BOOK_ID);
DROP INDEX idx_BOOKS ON BOOK_AUTHORS;
SHOW INDEXES FROM BOOK_AUTHORS;

Lab Programs – 4 AND 5 (On Aggregate Functions and Nested / Sub Queries) Title: Implement
nested sub queries (Single Row Query / Multiple Row Queries) While Creating Table Declare
constraints where ever required
1. Create Table Employees, using constraints on required columns (PK, NOT NULL, CHECK,
FK)
CREATE TABLE IF NOT EXISTS LOCATION (
LOCATION_ID INT NOT NULL PRIMARY KEY,
ADRESS VARCHAR(20) DEFAULT NULL,
POSTAL_CODE INT NOT NULL,
CITY VARCHAR(20) NOT NULL,
STATE_PROVINCE VARCHAR(20) DEFAULT NULL,
COUNTRY_ID VARCHAR(20) NOT NULL
);

DESC LOCATION;
CREATE TABLE IF NOT EXISTS Department (
DEPARTMENT_ID INT NOT NULL PRIMARY KEY,
DEPARTMENT_NAME VARCHAR(20) DEFAULT NULL,
MANAGER_ID INT UNIQUE NOT NULL,
LOCATION_ID INT DEFAULT NULL,
FOREIGN KEY (LOCATION_ID) REFERENCES LOCATION (LOCATION_ID)
);

DESC Department;

CREATE TABLE employees (


EMPLOYEE_ID DECIMAL(6,0) NOT NULL PRIMARY KEY,
FIRST_NAME VARCHAR(20) DEFAULT NULL,
LAST_NAME VARCHAR(25) NOT NULL,
EMAIL VARCHAR(25) NOT NULL,
PHONE_NUMBER VARCHAR(20) DEFAULT NULL,
HIRE_DATE DATE NOT NULL,
JOB_ID VARCHAR(10) NOT NULL,
SALARY DECIMAL(8,2) DEFAULT NULL,
COMMISSION_PCT DECIMAL(2,2) DEFAULT NULL,
MANAGER_ID INT DEFAULT NULL,
DEPARTMENT_ID INT,
FOREIGN KEY (DEPARTMENT_ID) REFERENCES Department (DEPARTMENT_ID)
);

DESC employees;

2. Insert values as in Location, Department and Employees table respectively.


INSERT INTO LOCATION VALUES (1000, 'Avenue', '989', 'Roma', 'Italy', 'IT');
INSERT INTO LOCATION VALUES (1100, 'Rashti', '10934', 'Venice', 'Italy', 'IT');
INSERT INTO LOCATION VALUES (1200, 'Shinju', '1689', 'Tokyo', 'Tokyo', 'JP');
INSERT INTO LOCATION VALUES (1400, 'Jabberwocky', '26192', 'Southlake', 'Michigan',
'US');
INSERT INTO LOCATION VALUES (1300, 'Shinju Rd', '6823', 'Tokoy', 'Texus', 'JP');

INSERT INTO Department VALUES (90, 'VP', 0, 1000);


INSERT INTO Department VALUES (100, 'Finance', 101, 1400);
INSERT INTO Department VALUES (30, 'Clerk', 114, 1200);
INSERT INTO Department VALUES (60, 'IT', 103, 1100);
INSERT INTO Department VALUES (70, 'Press', 110, 1300);

INSERT INTO employees


VALUES (100, 'Steven', 'King', 'SKING', '456789', '1987-06-17', 'AD_VP', 24000, 0, 0, 90);

INSERT INTO employees


VALUES (101, 'Neena', 'Kochhar', 'NKOCHHAR', '23646', '1987-06-18', 'AD_VP', 17000, 0,
100, 90);

INSERT INTO employees


VALUES (107, 'Diana', 'Lorentz', 'DLORENTZ', '15863', '1987-06-24', 'IT_PROG', 4200, 0, 103,
60);

INSERT INTO employees


VALUES (108, 'Nancy', 'Greenberg', 'NGREENBE', '79546', '1987-06-25', 'FI_MGR', 12000, 0,
101, 100);

INSERT INTO employees


VALUES (114, 'Den', 'Raphaely', 'DRAPHEAL', '79556', '1988-06-25', 'CLK', 11000, 0, 114,
30);
3. Write a SQL query to find those employees who receive a higher salary than the employee
with ID 114. Return first name, last name

SELECT first_name, last_name FROM employees


WHERE salary > ( SELECT salary
FROM employees WHERE employee_id=114
);

4. Write a SQL query to find those employees whose salary matches the lowest salary of any of
the departments. Return first name, last name and department ID.

SELECT first_name, last_name, salary, department_id FROM employees WHERE salary IN (


SELECT MIN(salary) FROM employees GROUP BY department_id );
5. write a SQL query to find those employees who earn more than the average salary. Return
employee ID, first name, last name

SELECT employee_id, first_name,last_name FROM employees WHERE salary > ( SELECT


AVG(salary) FROM employees );

6. write a SQL query to find all those employees who work in the IT department. Return
department ID, name (first), job ID and department name.

SELECT e.department_id, e.first_name, e.job_id , d.department_name FROM employees e ,


department d WHERE e.department_id = d.department_id AND d.department_name = 'IT';
7. write a SQL query to find those employees whose salary falls within the range of the smallest
salary and 10000. Return all the fields.

SELECT * FROM employees WHERE salary BETWEEN (SELECT MIN(salary) FROM


employees) AND 10000;

8. write a SQL query to find those employees who do not work in the departments where
managers’ IDs are between 100 and 110 (Begin and end values are included.). Return all the
fields of the employees.

SELECT * FROM employees WHERE department_id NOT IN (SELECT department_id FROM


department WHERE manager_id BETWEEN 100 AND 110);

9. write a SQL query to find those employees who get second-highest salary. Return all the fields
of the employees.

SELECT * FROM employees


WHERE employee_id IN (SELECT employee_id FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees WHERE salary < (SELECT
MAX(salary) FROM employees)));
10. write a SQL query to find those employees who earn more than the average salary and work
in the same department as an employee whose first name contains the letter 'S'. Return employee
ID, first name and salary.

SELECT employee_id, first_name , salary FROM employees


WHERE salary > (SELECT AVG (salary) FROM employees ) AND department_id IN (
SELECT department_id FROM employees WHERE first_name LIKE '%S%');

11. write a SQL query to calculate total salary of the departments where at least one employee
works. Return department ID, total salary

SELECT department.department_id, result1.total_amt FROM department, ( SELECT


employees.department_id, SUM(employees.salary) total_amt FROM employees GROUP BY
department_id) result1 WHERE result1.department_id = department.department_id;

Lab Program 5 - 5 (On Aggregate Functions and Nested / Sub Queries)


12. Write a query to display the employee id, name ( first name and last name ) and the job id
column with a modified title SALESMAN for those employees whose job title is ST_MAN and
DEVELOPER for whose job title is IT_PROG

SELECT employee_id, first_name, last_name, CASE job_id WHEN ' FI_MGR' THEN
‘MANAGER’ WHEN 'IT_PROG' THEN 'DEVELOPER' ELSE job_id END AS designation,
salary FROM employees;

13. write a SQL query to find those employees whose salaries exceed 50% of their department's
total salary bill. Return first name, last name.

SELECT e1.first_name, e1.last_name FROM employees e1 WHERE salary > ( SELECT


(SUM(salary))*.5 FROM employees e2 WHERE e1.department_id=e2.department_id);
14. write a SQL query to find those employees who manage a department. Return all the fields of
employees table.

SELECT * FROM employees WHERE employee_id=ANY ( SELECT manager_id FROM


department );

15. write a SQL query to find those managers who supervise four or more employees. Return
manager name, department ID.

SELECT first_name || ' ' || last_name AS Manager_name,department_id FROM employees


WHERE employee_id IN (SELECT manager_id FROM employees GROUP BY manager_id
HAVING COUNT(*)>=1);
16. write a SQL query to find the first name, last name, department, city, and state province for
each employee.

SELECT E.first_name,E.last_name, D.department_name, L.city, L.state_province FROM


employees E JOIN department D ON E.department_id = D.department_id JOIN location L ON
D.location_id = L.location_id;

17. write a SQL query to find the employees and their managers. These managers do not work
under any manager. Return the first name of the employee and manager .

SELECT E.first_name AS "Employee Name", M.first_name AS "Manager" FROM employees


E LEFT OUTER JOIN employees M ON E.manager_id = M.employee_id;
18. write a SQL query to calculate the average salary, the number of employees receiving
commissions in that department. Return department name, average salary and number of
employees .

SELECT department_name, AVG(salary), COUNT(commission_pct) FROM department JOIN


employees USING (department_id) GROUP BY department_name;

19. write a SQL query to find the department name, department ID, and number of employees in
each department.

SELECT d.department_name, e.* FROM department d JOIN (SELECT count(employee_id),


department_id FROM employees GROUP BY department_id) e USING (department_id);

PRACTICE :
20. write a SQL query to find those employees who earn more than the average salary. Sort the
result-set in descending order by salary. Return first name, last name, salary, and department ID.
SELECT first_name, last_name , salary, department_id FROM employees WHERE salary > (
SELECT AVG(salary) FROM employees ) ORDER BY salary DESC;

21. write a SQL query to find the first name, last name, department number, and department
name for each employee

SELECT E.first_name , E.last_name , E.department_id , D.department_name FROM employees


E JOIN department D ON E.department_id = D.department_id;

Lab Programs – 6 AND 7 (Stored Procedures)


Stored Procedure Programs with -
1. Simple SP creation and calling
2. SP using IN
3. SP using out
4. SP using INOUT
5. Drop Procedure
6. Display procedures used in DB
7. Definition of Stored Procedures
8. Nested Stored Procedures
9. Using Conditional Stored Procedures

Note use previously created Employees table to perform the below Programs

1. Write a SQL query to find those employees whose salary is lowest / Highest / Avg salary by
the departments

a) Lowest Salary

USE Employees;
SHOW PROCEDURE STATUS WHERE Db = 'Employees';

DROP PROCEDURE IF EXISTS my_proc_Min_Sal;

DELIMITER //
CREATE PROCEDURE my_proc_Min_Sal()
BEGIN
SELECT department_id, MIN(salary) AS Min_Salary
FROM employees -- Make sure "employees" table exists
GROUP BY department_id;
END//
DELIMITER ;

CALL my_proc_Min_Sal();
b) Highest salary

DELIMITER //
CREATE PROCEDURE my_proc_Max_Sal()
BEGIN
SELECT department_id, MAX(salary) AS Max_Salary
FROM employees
GROUP BY department_id;
END//
DELIMITER ;
CALL my_proc_Max_Sal();
c) Average salary

DELIMITER //
CREATE PROCEDURE my_proc_Avg_Sal()
BEGIN
SELECT department_id, AVG(salary) AS Avg_Salary
FROM employees
GROUP BY department_id;
END//
DELIMITER ;
CALL my_proc_Avg_Sal();

2. Write a SQL query to find those employees who earn more than the average salary. Sort the
result-set in descending order by salary. Return first name, last name, salary, and department ID.

DELIMITER //

CREATE PROCEDURE my_proc_Morethan_AVG_Sal()


BEGIN
SELECT first_name, last_name, salary, department_id
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
)
ORDER BY salary DESC;
END //

DELIMITER ;
CALL my_proc_Morethan_AVG_Sal();
3. Write a SQL query to find the first name, last name, department number, and department name
for each employee

To Create a parameterized stored procedure – Syntax


(IN | OUT | INOUT) (Parameter Name [datatype(length)])

DELIMITER //

CREATE PROCEDURE my_proc_emp_dept_details()


BEGIN
SELECT e.first_name, e.last_name, e.department_id, d.department_name
FROM employees e
JOIN department d ON e.department_id = d.department_id;
END //

DELIMITER ;

CALL my_proc_emp_dept_details();
4. Write a SQL query to find those employees who receive a higher salary than the employee
with ID 114. Return first name, last name (/* IN Parameter*/)

DELIMITER //

CREATE PROCEDURE empl_info(IN empl_id INTEGER)


BEGIN
SELECT employee_id, first_name, last_name
FROM employees
WHERE salary > (
SELECT salary
FROM employees
WHERE employee_id = empl_id
);
END //

DELIMITER ;

CALL empl_info(114);

5. Write a SQL query to calculate the number of employees receiving salary more than 10000.
Return number of employees. (/* OUT Parameter*/)

DELIMITER //

CREATE PROCEDURE empl_info_Out(OUT Emp INT)


BEGIN
SELECT COUNT(*) INTO Emp
FROM department
JOIN employees USING (department_id)
WHERE salary >= 10000;
END //

DELIMITER ;

/* To store the value returned by the procedure, needs to be passed to a session variable named
@Emp_Count */

-- Calling the procedure and storing result in a session variable


CALL empl_info_Out(@Emp_Count);
SELECT @Emp_Count AS Employee_Sal;

/* Expected Solution– Query should return, total number of employees having salary >=10000 */

6. Write a SQL query to find those employees who receive a higher salary than the employee
with ID declared IN Parameter. Return Count of Employees whose salary is greater than
Employee ID passed in the IN parameter (/* INOUT Parameter*/)

DELIMITER //

CREATE PROCEDURE empl_info_InOut(INOUT Emp_Sal INTEGER, IN empl_id


INTEGER)
BEGIN
SELECT COUNT(employee_id) INTO Emp_Sal
FROM employees
WHERE salary > (
SELECT salary
FROM employees
WHERE employee_id = empl_id
);
END //

DELIMITER ;
-- Calling the procedure and storing result in a session variable
CALL empl_info_InOut(@Emp_Sal, 114);
SELECT @Emp_Sal AS No_of_Emp;

/* Expected Solution – Count of Employees whose salary is greater than the salary of Parameter
passed Employee Id is displayed. */

7. Command to see the definition of Created Procedures

SHOW CREATE PROCEDURE empl_info_Out;

8. View the list of stored procedure in a database using a query


- Displays list of Procedures used in DB

SELECT routine_name, routine_type, definer, created, security_type, SQL_Data_Access


FROM information_schema.routines
WHERE routine_type = 'PROCEDURE'
AND routine_schema = 'employees';
(OR)

SHOW PROCEDURE STATUS WHERE name LIKE '%Emp%';

9. Drop the existing Procedure from the database.

DROP PROCEDURE IF EXISTS `employees`.`my_proc_Morethan_AVG_Sal`;


SHOW PROCEDURE STATUS WHERE Db = 'employees';

Program 7 - Set 2 - Practice Stored Procedure Queries –


1. CREATE SCHEMA stored_proc

2. CREATE TABLE studentMarks (stud_id SMALLINT(5) NOT NULL AUTO_INCREMENT


PRIMARY KEY, total_marks INT, grade VARCHAR(5));

3. Insert sample data —


INSERT INTO stored_proc.studentMarks (total_marks, grade)
VALUES
(450, 'A'),
(480, 'A+'),
(490, 'A++'),
(440, 'B+'),
(400, 'C+'),
(380, 'C'),
(250, 'D'),
(200, 'E'),
(100, 'F'),
(150, 'F'),
(220, 'E');

4. Create Simple Stored Procedure to return all records from Student Marks table

DELIMITER $$

CREATE PROCEDURE stored_proc.GetStudentData()


BEGIN
SELECT * FROM stored_proc.studentMarks;
END $$

DELIMITER ;

CALL stored_proc.GetStudentData();
5. Create a procedure to fetch the details of students with the student ID being passed as an Input
parameter.

DELIMITER //

CREATE PROCEDURE stored_proc.spGetDetailsByStudentName(IN studentId INT)


BEGIN
SELECT * FROM stored_proc.studentMarks
WHERE stud_id = studentId;
END //

DELIMITER ;

CALL stored_proc.spGetDetailsByStudentName(1);
6. To calculate the average marks of all the students from the studentMarks table and return the
average as an OUT field.

DELIMITER //

CREATE PROCEDURE stored_proc.spGetAverageMarks(OUT average DECIMAL(5,2))


BEGIN
SELECT AVG(total_marks) INTO average FROM stored_proc.studentMarks;
END //

DELIMITER ;

CALL stored_proc.spGetAverageMarks(@average_marks);
SELECT @average_marks;

7. Find the count of students who is having marks below the average marks of all the students
using Local variables

DELIMITER //

CREATE PROCEDURE stored_proc.spCountOfBelowAverage(OUT countBelowAverage INT)


BEGIN
DECLARE avgMarks DECIMAL(5,2) DEFAULT 0;

-- Calculate average marks and store in avgMarks


SELECT AVG(total_marks) INTO avgMarks FROM stored_proc.studentMarks;
-- Count students with marks below the average
SELECT COUNT(*) INTO countBelowAverage
FROM stored_proc.studentMarks
WHERE total_marks < avgMarks;
END //

DELIMITER ;

-- Calling the procedure


CALL stored_proc.spCountOfBelowAverage(@countBelowAverage);

-- Retrieve the output parameter value


SELECT @countBelowAverage;

8. To fetch the highest marks from a student data table. We can have one like this with the
highest marks stored in an OUT parameter.

DELIMITER //

CREATE PROCEDURE stored_proc.spGetMaxMarks(OUT highestMarks INT)


BEGIN
-- Get the highest marks from the studentMarks table
SELECT MAX(total_marks) INTO highestMarks FROM stored_proc.studentMarks;
END //

DELIMITER ;

-- Calling the procedure


CALL stored_proc.spGetMaxMarks(@highestMarks);

-- Retrieve the output parameter value


SELECT @highestMarks;

9. Calling A Procedure From Another STORED PROCEDURE -

(Nested Procedure) Call a procedure from another procedure to return the overall result of a
student. If student marks are above average – then the result would be PASS else – FAIL

Solution - create 2 procedures


a. Procedure for calculating Average marks and creating Boolean values for the results

DELIMITER $$

CREATE PROCEDURE stored_proc.spGetIsAboveAverage(IN studentId INT, OUT


isAboveAverage BOOLEAN)
BEGIN
DECLARE avgMarks DECIMAL(5,2) DEFAULT 0;
DECLARE studMarks INT DEFAULT 0;

-- Calculate the average marks of all students


SELECT AVG(total_marks) INTO avgMarks FROM stored_proc.studentMarks;

-- Get the total marks of the given student


SELECT total_marks INTO studMarks FROM stored_proc.studentMarks
WHERE stud_id = studentId;

-- Check if the student's marks are above the average


IF studMarks > avgMarks THEN
SET isAboveAverage = TRUE;
ELSE
SET isAboveAverage = FALSE;
END IF;
END $$

DELIMITER ;

b. Declaring Students results with Boolean values based on Students marks

DELIMITER $$

CREATE PROCEDURE stored_proc.spGetStudentResult(IN studentId INT, OUT result


VARCHAR(20))
BEGIN
-- Call the first procedure to check if the student is above average
CALL stored_proc.spGetIsAboveAverage(studentId, @isAboveAverage);

-- Determine the result based on the boolean value returned


IF @isAboveAverage = 0 THEN
SET result = "FAIL";
ELSE
SET result = "PASS";
END IF;
END $$

DELIMITER ;

c) Calling the Procedure to Fetch Results


– For PASS (Student ID: 2, Total Marks: 450)

CALL stored_proc.spGetStudentResult(2, @result);


SELECT @result;

– For FAIL (Student ID: 10, Total Marks: 150)

CALL stored_proc.spGetStudentResult(10, @result);


SELECT @result;

10. Write a procedure to take studentId and depending on the studentMarks we need to return the
class according to the below criteria. ( Using Conditional statements)

Marks >= 400 : Class – First Class


Marks >= 300 and Marks < 400 – Second Class
Marks < 300 – Failed

DELIMITER $$
CREATE PROCEDURE stored_proc.spGetStudentClass(IN studentId INT, OUT class
VARCHAR(20))
BEGIN
DECLARE marks INT DEFAULT 0;

-- Get the student's total marks


SELECT total_marks INTO marks FROM stored_proc.studentMarks
WHERE stud_id = studentId;

-- Determine the class based on marks


IF marks >= 400 THEN
SET class = "First Class";
ELSEIF marks >= 300 AND marks < 400 THEN
SET class = "Second Class";
ELSE
SET class = "Failed";
END IF;
END $$

DELIMITER ;

a. For student ID – 1 – total_marks are 450 – hence the expected result is FIRST CLASS.

CALL stored_proc.spGetStudentClass(1, @class);


SELECT @class;

b. For student ID – 6 – total_marks is 380 – Hence the expected result is SECOND CLASS
CALL stored_proc.spGetStudentClass(6, @class);
SELECT @class;

c. For student ID – 11 – total_marks are 220 – Hence expected result is FAILED.


CALL stored_proc.spGetStudentClass(11, @class);
SELECT @class;

Using Handler Within STORED PROCEDURE Body –

11. Create a procedure that would insert a record in the studentMarks table and have IN
parameters as studentId, total_marks, and grade. We are also adding an OUT parameter named
rowCount which would return the total count of records in the studentMarks table. Add the EXIT
Error Handler for Duplicate Key record i.e. if someone invokes it for inserting a record with an
existing studentID, then the Error handler would be invoked and will return an appropriate error.

DELIMITER $$

CREATE PROCEDURE stored_proc.spInsertStudentData(


IN studentId INT,
IN total_marks INT,
IN grade VARCHAR(20),
OUT rowCount INT
)
BEGIN
-- Error handler declaration for duplicate key
DECLARE EXIT HANDLER FOR 1062
BEGIN
SELECT 'DUPLICATE KEY ERROR' AS errorMessage;
END;

-- Insert the student record


INSERT INTO stored_proc.studentMarks(stud_id, total_marks, grade)
VALUES (studentId, total_marks, grade);

-- Count total records in the table


SELECT COUNT(*) INTO rowCount FROM stored_proc.studentMarks;
END $$

DELIMITER ;

-- Calling the procedure with an existing student ID (to trigger error)


CALL stored_proc.spInsertStudentData(1, 450, 'A+', @rowCount);

– The output would display an error message defined in the error handler. Since it’s an exit
handler, the main procedure flow would not continue.

– Hence, in this case the rowCount OUT parameter would not be updated as this statement is
after the INSERT statement that had generated the error condition.

– If you,Retrieve the value of rowCount, you would get NULL.

-- Fetch the value of rowCount (Will return NULL if error occurred)


SELECT @rowCount;
12. Create a procedure that would insert a record in the studentMarks table and have IN
parameters as studentId, total_marks, and grade. We are also adding an OUT parameter named
rowCount which would return the total count of records in the studentMarks table. Add the
CONTINUE Error Handler for Duplicate Key record i.e. if someone invokes it for inserting a
record with an existing studentID, then the Error handler would be invoked and will return an
appropriate error but will continue the execution after handling the error code.

(Query same as 11 but with CONTINUE handler)

DROP this procedure, and re-create with CONTINUE action instead of EXIT for the error
handler.

(-- Drop the existing procedure before recreating)

DROP PROCEDURE IF EXISTS stored_proc.spInsertStudentData;

DELIMITER $$

CREATE PROCEDURE stored_proc.spInsertStudentData(


IN studentId INT,
IN total_marks INT,
IN grade VARCHAR(20),
OUT rowCount INT
)
BEGIN
-- Error handler for duplicate key, but allows execution to continue
DECLARE CONTINUE HANDLER FOR 1062
BEGIN
SELECT 'DUPLICATE KEY ERROR' AS errorMessage;
END;
-- Insert the student record
INSERT INTO stored_proc.studentMarks(stud_id, total_marks, grade)
VALUES (studentId, total_marks, grade);

-- Count total records in the table (This will execute even if an error occurs)
SELECT COUNT(*) INTO rowCount FROM stored_proc.studentMarks;
END $$

DELIMITER ;

-- Calling the procedure with an existing student ID (to trigger error)


CALL stored_proc.spInsertStudentData(1, 450, 'A+', @rowCount);

-- Fetch the updated value of rowCount (Will still update despite error)
SELECT @rowCount;

You might also like