Advance Database Management System (ADBMS) - MECS -672
Lab File
Submitted To
Mr. Pramod Soni
From
Sachin Bhardwaj
01216424820
Contents
1. Assignment: Part-1, Create Tables .................................................................................................. 3
2. Assignment: Part-2, Select Queries................................................................................................. 4
3. Assignment: Create Tables with Keys & Select Queries. .............................................................. 10
4. Assignment: Data Retrieval based on Conditions. ........................................................................ 16
5. Assignment Queries: Date Functions, Maths Functions, String Functions ................................... 19
6. Assignment: Views ........................................................................................................................ 21
7. Assignment: Procedures ............................................................................................................... 23
8. Assignment- Functions .................................................................................................................. 26
9. Assignment- Triggers..................................................................................................................... 27
10. Assignment- Cursor ................................................................................................................... 29
1. Assignment: Part-1, Create Tables
Create database MTECHCSE;
Use MTECHCSE;
CREATE Table Worker(WORKER_ID int, FIRST_NAME varchar(100), LAST_Name varchar(50), SALARY
int, JOINING_DATE datetime, DEPARTMENT varchar(50));
INSERT INTO Worker VALUES
('001', 'Monika',' Arora', '100000', '2014-02-20 [Link]','HR'),
('002' ,'Niharika',' Verma', '80000', '2014-06-11 [Link]', 'Admin'),
('003', 'Vishal',' Singhal', '300000', '2014-02-20 [Link]', 'HR'),
('004', 'Amitabh',' Singh', '500000', '2014-02-20 [Link]', 'Admin'),
('005', 'Vivek',' Bhati', '500000','2014-06-11 [Link]','Admin'),
('006', 'Vipul',' Diwan', '200000', '2014-06-11 [Link]', 'Account'),
('007', 'Satish',' Kumar', '75000', '2014-01-20 [Link]', 'Account'),
('008', 'Geetika',' Chauhan', '90000', '2014-04-11 [Link]', 'Admin');
Select * from Worker;
CREATE Table Bonus(WORKER_REF_ID int, BONUS_DATE datetime,BONUS_AMOUNT int);
INSERT INTO Bonus VALUES
('1', '2016-02-20 [Link]', '5000'),
('2', '2016-06-11 [Link]','3000'),
('3', '2016-02-20 [Link]', '4000'),
('1', '2016-02-20 [Link]', '4500'),
('2', '2016-06-11 [Link]', '3500');
Select * from Bonus;
CREATE Table Title(WORKER_REF_ID int, WORKER_TITLE varchar(50), AFFECTED_FROM datetime);
INSERT INTO Title VALUES
('1',' Manager','2016-02-20 [Link]'),
('2',' Executive',' 2016-06-11 [Link]'),
('8',' Executive',' 2016-06-11 [Link]'),
('5',' Manager',' 2016-06-11 [Link]'),
('4',' Asst. Manager','2016-06-11 [Link]'),
('7',' Executive',' 2016-06-11 [Link]'),
('6',' Lead',' 2016-06-11 [Link]'),
('3','Lead',' 2016-06-11 [Link]');
Select * from Title;
2. Assignment: Part-2, Select Queries
Performs the following queries on the table created in part 1 of assignment given above.
1. Write an SQL query to fetch “FIRST_NAME” from Worker table using the alias name as
<WORKER_NAME>.
Select FIRST_NAME from Worker as WORKER_NAME;
2. Write an SQL query to fetch “FIRST_NAME” from Worker table in upper case.
Select Upper(FIRST_NAME) from Worker as WORKER_NAME;
3. Write an SQL query to fetch unique values of DEPARTMENT from Worker table.
Select Distinct(DEPARTMENT) from Worker as WORKER_NAME;
4. Write an SQL query to print the first three characters of FIRST_NAME from Worker table.
Select Left(FIRST_NAME,3) from Worker as WORKER_NAME;
5. Write an SQL query to find the position of the alphabet (‘a’) in the first name column
‘Amitabh’ from Worker table.
Select position('A' in FIRST_NAME) from Worker as WORKER_NAME;
6. Write an SQL query to print the FIRST_NAME from Worker table after removing white
spaces from the right side.
Select rtrim(FIRST_NAME) from Worker as WORKER_NAME;
7. Write an SQL query to print the DEPARTMENT from Worker table after removing white
spaces from the left side.
Select ltrim(DEPARTMENT) from Worker as WORKER_NAME;
8. Write an SQL query that fetches the unique values of DEPARTMENT from Worker table
and prints its length.
Select Distinct(DEPARTMENT), length(DEPARTMENT) from Worker as WORKER_NAME;
9. Write an SQL query to print the FIRST_NAME from Worker table after replacing ‘a’ with
‘A’.
SELECT REPLACE(FIRST_NAME, 'a', 'A') from Worker as WORKER_NAME;
10. Write an SQL query to print the FIRST_NAME and LAST_NAME from Worker table into a
single column COMPLETE_NAME. A space char should separate them.
Select concat(FIRST_NAME," ",LAST_NAME) As 'COMPLETE_Name' from Worker as
WORKER_NAME;
11. Write an SQL query to print all Worker details from the Worker table order by
FIRST_NAME Ascending.
Select FIRST_NAME from Worker as WORKER_NAME order by FIRST_NAME asc;
12. Write an SQL query to print all Worker details from the Worker table order by
FIRST_NAME Ascending and DEPARTMENT Descending.
Select * from Worker as WORKER_NAME order by FIRST_NAME asc, DEPARTMENT desc;
13. Write an SQL query to print details for Workers with the first name as “Vipul” and “Satish”
from Worker table.
Select * from Worker as WORKER_NAME where FIRST_NAME='Satish' or FIRST_NAME='Vipul';
14. Write an SQL query to print details of workers excluding first names, “Vipul” and “Satish”
from Worker table.
Select * from Worker as WORKER_NAME where FIRST_NAME <> 'Satish' and FIRST_NAME <>
'Vipul';
15. Write an SQL query to print details of Workers with DEPARTMENT name as “Admin”.
Select * from Worker as WORKER_NAME where DEPARTMENT='Admin';
16. Write an SQL query to print details of the Workers whose FIRST_NAME contains ‘a’.
Select * from Worker as WORKER_NAME where FIRST_NAME Like '%a%';
17. Write an SQL query to print details of the Workers whose FIRST_NAME ends with ‘a’.
Select * from Worker as WORKER_NAME where FIRST_NAME Like '%a';
18. Write an SQL query to print details of the Workers whose FIRST_NAME ends with ‘h’ and
contains six alphabets.
Select * from Worker as WORKER_NAME where FIRST_NAME Like '_____%h';
19. Write an SQL query to print details of the Workers whose SALARY lies between 100000
and 500000.
Select * from Worker as WORKER_NAME where SALARY between 100000 and 500000;
20. Write an SQL query to print details of the Workers who have joined in Feb’2014.
Select * from Worker as WORKER_NAME where extract(Month from JOINING_DATE)= 2 and
extract(Year from JOINING_DATE)=2014;
3. Assignment: Create Tables with Keys & Select Queries.
Create a Database for an Organization and create the following tables in the Organization
Database:
create database Organization;
Use Organization;
-------------------Insert a minimum of 20 records in each table----------------
Employee(EMP_ID(PK),FIRST_NAME,LAST_NAME,SALARY, JOINING_DATE, DEPARTMENT)
CREATE Table Employee(EMP_ID int, FIRST_NAME varchar(100), LAST_Name varchar(50), SALARY
int, JOINING_DATE datetime, DEPARTMENT varchar(50),PRIMARY KEY (EMP_ID));
Bonus (EMP_REF_ID(FK EMP_ID),BONUS_AMOUNT,BONUS_DATE)
CREATE Table Bonus(EMP_REF_ID int, BONUS_AMOUNT int, BONUS_DATE datetime, FOREIGN KEY
(EMP_REF_ID) REFERENCES Employee(EMP_ID));
Title (EMP_REF_ID(FKEMP_ID),EMP_TITLE,AFFECTED_FROM)
CREATE Table Title(EMP_REF_ID int, EMP_TITLE varchar(100), AFFECTED_FROM datetime, FOREIGN
KEY (EMP_REF_ID) REFERENCES Employee(EMP_ID));
Retrieve the following information from the Organization database:
1. SQL query to fetch “FIRST_NAME” from Employee table using the alias name as
<Employee_NAME>.
Select FIRST_NAME from Employee as EMPLOYEE_NAME;
2. SQL query to fetch “FIRST_NAME” from Employee table in upper case.
Select UPPER(FIRST_NAME) from Employee as EMPLOYEE_NAME;
3. SQL query to fetch unique values of DEPARTMENT from Employee table.
Select Distinct(DEPARTMENT) from Employee;
4. SQL query to print the first three characters of FIRST_NAME from Employee table.
Select Left(FIRST_NAME,3) from Employee;
5. SQL query to print all Employee details from the Employee table order by FIRST_NAME
Ascending and DEPARTMENT Descending.
Select * from Employee as EMPLOYEE_NAME order by FIRST_NAME asc, DEPARTMENT desc;
6. SQL query to fetch the count of employees working in the department ‘Admin’.
Select count(DEPARTMENT) from Employee where DEPARTMENT='Admin';
7. SQL query to fetch Employee names with salaries >= 50000 and <= 100000.
Select * from Employee as EMPLOYEE_NAME where SALARY between 50000 and 100000;
8. SQL query to print details of the Workers who are also Managers.
SELECT * FROM Employee INNER JOIN Title ON Employee.EMP_ID=Title.EMP_REF_ID and
Title.EMP_TITLE='Manager';
9. SQL query to fetch duplicate records having matching data in some fields of a table.
select * from Employee where EMP_ID not in (select EMP_REF_ID from Title);
10. SQL query to show only odd rows from a table
Select * from Employee where mod(EMP_ID,2)<>0;
11. SQL query to show only even rows from a table.
Select * from Employee where mod(EMP_ID,2)=0;
12. SQL query to show records from one table that another table does not have
select * from Employee where EMP_ID not in (select EMP_REF_ID from Title);
13. SQL query to show the top n (say 10) records of a table.
SELECT * FROM Employee limit 10;
14. SQL query to fetch the first 50% records from a table.
SELECT * from Employee where EMP_ID<=(SELECT COUNT(*)/2 FROM Employee);
15. SQL query to show all departments along with the number of people in there.
Select department, count(*) from Employee group by DEPARTMENT;
16. SQL query to show the last record from a table.
select * from Employee order by EMP_ID desc limit 1;
4. Assignment: Data Retrieval based on Conditions.
Department and Employee Table Creation and Insertion of Data:
1. CREATE Table Department(DNAME varchar(100),DNO int, MGRSSN int, MGRSTARTDATE
datetime,PRIMARY KEY (DNO));
INSERT INTO Department VALUES
('Research', '5', '23423423', '2014-02-20'),
('Administration' , '4','23444234', '2014-06-11'),
('Headquearters', '1','5643534', '2014-02-20');
2. CREATE Table Employee(FIRST_NAME varchar(100),MNIT varchar(100), LAST_Name
varchar(50), SSN varchar(100),BDATE datetime, ADDRESS varchar(200), SEX varchar(100),
SALARY int,SUPERSSN varchar(100) ,DNO int, FOREIGN KEY (DNO) REFERENCES
Department(DNO));
INSERT INTO Employee VALUES
('Monika','B',' Arora', '32423423', '1937-02-20','34695 R,
Hudosn','F','345434','34534534','5'),
('Niharika','T',' Verma', '8023000', '1990-06-11', '13134 R,
HFGudosn','F','3444534','34534534','5'),
('Vishal','J',' Singhal', '30054000', '1995-02-20', '2436 R,
HuVBdosn','M','13434534','34534534','4'),
('Amitabh','S',' Singh', '4363654', '1955-02-20', '94354 R,
HuXdosn','M','34877534','34534534','4'),
('Vivek','K',' Bhati', '54654','1937-06-11','1213 R, HVBudosn','M','45645345','34534534','5'),
('Vipul','A',' Diwan', '56454577', '1972-06-11', '7889 R,
GHRD','M','7754345','34534534','5'),
('Satish','V',' Kumar', '0963452', '1998-01-20', '3466795 R,
HXSFudosn','M','223434534','34534534','4'),
('Geetika','E','Chauhan', '23545756', '1965-04-11', '3423 R,
HudSGERosn','F','14534534','34534534','1');
Q:1
UPDATE Employee AS E, Department AS D SET [Link]= [Link] + ([Link] * 0.1) WHERE
[Link]=[Link] and [Link]='Research';
SELECT E.FIRST_NAME, [Link] from Employee AS E, Department as D where [Link]=[Link] and
[Link]='Research';
Q:2:
Select sum(SALARY), Avg(SALARY), min(SALARY), max(SALARY) from Employee As E,Department as D
where [Link]=[Link] and [Link]='Administration';
Q:3:
SELECT E.FIRST_NAME from Employee AS E where [Link]=5;
Q:4:
SELECT [Link], COUNT(*) FROM Department as D, Employee As E where [Link]=[Link] GROUP
BY [Link] having Count(*)>2;
Q:5:
Select E.FIRST_NAME from Employee As E where extract(Year from BDATE)>1989 and extract(Year
from BDATE)<2000;
Q:6:
SELECT E.FIRST_NAME, [Link] from Employee AS E INNER JOIN Department as D where
[Link]=[Link];
5. Assignment Queries: Date Functions, Maths Functions, String
Functions
• Select SYSDATE() As SystemDate, Extract(day from SYSDATE()) As CurrentDay,Extract(Month
from SYSDATE()) As CurrentMonth,Extract(Year from SYSDATE()) As CurrentYear;
• Select curtime() As Time, curdate() As CurrentDate, dayname(curdate()) As DayName,
weekday(curdate()) As WeekDay;
• SELECT STR_TO_DATE('[Link] PM',GET_FORMAT(TIME,'USA')) As USATime;
• SELECT ADDDATE(curdate(), INTERVAL 4 Week) as AfterWeeks, ADDDATE(curdate(),
INTERVAL 10 Day) as AfterDays,ADDDATE(curdate(), INTERVAL 2 month) as AfterMonths;
• SELECT DATEDIFF(ADDDATE(curdate(), INTERVAL 10 Week),curdate()) As DifferenceInDays;
• SELECT DATE_FORMAT(NOW(), '%Y %m') As Format;
• SELECT POW(3, 2), abs(13.55), sin(11),cos(1.12), tan(4.5), ceil(45.5), 33445 div 3;
• Select exp(5), floor(23.67), greatest(4,5,3,9,0),least(4,3,2,7),log10(45.55);
• Select ascii('Sachin') As FirstCharacter, char_length('Sachin') AS LengthOfString,
CONCAT('Sachin',' Bhardwaj') AS FullName, FIND_IN_SET("q", "s,q,l") As Position;
• SELECT lcase('THIS IS THE BEST') As SmallLetter , ucase('this is the best') As CapitalLetter,
LEFT('this is the best', 3) As LeftSideString, LENGTH('this is the best') AS LengthOfString;
• SELECT REPLACE('These are query strings', 'are', 'are not') As ReplacedString, REVERSE('These
are query strings') As ReversedString;
• SELECT SUBSTRING('These are query strings', 7, 3) AS SubString, SUBSTRING_INDEX('These
are query strings', "q", 1) As SplitData;
• SELECT CONVERT(198, CHAR),CONVERT('2019-11-19', DATETIME), CONVERT("[Link]",
TIME), STR_TO_DATE("August 10 2017", "%M %d %Y");
6. Assignment: Views
Use Organization; -→Database
• Create View EmployeeView As Select emp_id, first_name, joining_date from employee
where department='HR';
Select * from EmployeeView;
• Create View EmployeeInformation As select e.emp_id, e.first_name,[Link],
b.bonus_amount, b.bonus_date from bonus As b, employee As e where
[Link]='Admin' and e.emp_id=b.emp_ref_id;
Select * from EmployeeInformation;
• Updatable View, with no constraints:
Create View WorkerView As Select WORKER_ID, FIRST_NAME from Worker;
INSERT INTO WorkerView VALUES ('8','abc'),('9','xyz');
Main Worker Table After inserting in workerview
WorkerView:
• Updatable View with constraints, add the values in both parent table and view table if view
has including all not null attributes.
Insert the values in View including not null attributes, it inserts the values in the main table.
INSERT INTO EmployeeView VALUES
('030', 'NewEmployee1','2021-02-20 [Link]'),
('031' ,'NewEmployee2','2021-03-20 [Link]');
• It will throw the error as it doesn’t include all not null attributes.
Create View EmployeeViewA2 As Select first_name, joining_date from employee where
department='Admin';
INSERT INTO EmployeeViewA2 VALUES
('abc','2021-02-20 [Link]'),
('xyz','2021-03-20 [Link]');
• Drop View WorkerView;
7. Assignment: Procedures
1. Add two numbers
DELIMITER &&
create procedure add_numbers(n1 int, n2 int)
BEGIN
select n1+n2 as Sum;
END &&
DELIMITER ;
Call ADD_NUMBERS(5,5);
2. Concatenate by declaring local variables:
DELIMITER &&
create procedure looper(my_string varchar(100))
BEGIN
declare temp_string varchar(100);
Set temp_string=" are you doing?";
Set temp_string = CONCAT( my_string,temp_string);
Select temp_string As Result;
END &&
DELIMITER ;
3. If/Else Conditions
DELIMITER &&
create procedure conditional(n1 int, n2 int)
BEGIN
if(n1>n2) then
select n1*n2 as Multiply;
else
select n1+n2 as Sum;
end if;
END &&
DELIMITER ;
Call conditional(10,5);
Call conditional(5,10);
4. Loops
For Loop or Normal Loop:
DELIMITER &&
create procedure looping(n1 int, n2 int)
BEGIN
loop_label: loop
IF n1 > n2 THEN
LEAVE loop_label;
END IF;
Select n1+n2;
SET n1 = n1 + 1;
ITERATE loop_label;
END loop;
END &&
DELIMITER ;
Call looping(5,10);
While Loop:
DELIMITER &&
create procedure looping1(my_string varchar(100), num int)
BEGIN
WHILE num <= 10 DO
Set my_string = CONCAT(my_string,num,',');
Set num = num + 1;
END WHILE;
Select my_string As Result;
END &&
DELIMITER ;
Call looping1("S",0);
Repeat- Until Loop:
DELIMITER &&
create procedure looping2(my_string varchar(100), num int)
BEGIN
REPEAT
SET my_string = CONCAT(my_string,num,',');
SET num = num + 1;
UNTIL num > 5
END REPEAT;
Select my_string As Result;
END &&
DELIMITER ;
Call looping2("What",0);
8. Assignment- Functions
Use organization;
################################################### Function 1
DELIMITER //
CREATE function CalculateIncome( initialIncome int ) RETURNS INT DETERMINISTIC
BEGIN
DECLARE incomefactor INT;
SET incomefactor = 2;
Set initialIncome = initialIncome * incomefactor;
RETURN initialIncome;
END //
DELIMITER ;
Select Emp_id, First_name, Last_name,salary, CalculateIncome(salary) as 'After Increment' from
employee;
Select CalculateIncome (10000); ##Select is Working
################################################### Procedure
DELIMITER $$
create procedure add_numbers(n1 int, n2 int)
BEGIN
select n1+n2 as Sum;
END
DELIMITER $$;
Call ADD_NUMBERS(5,5); ##Call is Working
################################################### Function 2
DELIMITER //
CREATE FUNCTION no_of_years(date1 date) RETURNS int DETERMINISTIC
BEGIN
DECLARE date2 DATE;
Select current_date()into date2;
RETURN year(date2)-year(date1);
END //
DELIMITER ;
Select Emp_id, First_name, Last_name, no_of_years(joining_date) as 'Years' from employee;
9. Assignment- Triggers
Bonus Table:
Create TRIGGER ON Insert:
1. CREATE TRIGGER bonus_sum BEFORE INSERT ON bonus
FOR EACH ROW SET @sum = @sum + NEW.bonus_amount;
2. SET @sum = 0;
3. INSERT INTO bonus VALUES(31,746573,"2020-06-11 [Link]");
4. SELECT @sum AS 'Total amount inserted';
10. Assignment- Cursor
CREATE DEFINER=`root`@`localhost` PROCEDURE `new_curdemo`(
INOUT emailList varchar(4000)
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE emailAddress char(100) DEFAULT "";
DEClARE curEmail CURSOR FOR SELECT Email_ID FROM EmpData;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN curEmail;
getEmail: LOOP
FETCH curEmail INTO emailAddress;
IF finished = 1 THEN
LEAVE getEmail;
END IF;
-- build email list
SET emailList = CONCAT(emailAddress,";",emailList);
END LOOP getEmail;
CLOSE curEmail;
END