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

New Text DocumentS

The document provides SQL queries for creating and managing employee and department tables, including operations like creating, modifying, and dropping tables and columns. It also includes queries for inserting data, selecting specific records, and performing calculations such as average salary and total payroll. Additionally, it demonstrates the use of various SQL functions for string manipulation and data retrieval.

Uploaded by

Subham Garain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

New Text DocumentS

The document provides SQL queries for creating and managing employee and department tables, including operations like creating, modifying, and dropping tables and columns. It also includes queries for inserting data, selecting specific records, and performing calculations such as average salary and total payroll. Additionally, it demonstrates the use of various SQL functions for string manipulation and data retrieval.

Uploaded by

Subham Garain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 34

-- 5.

Write a query to create a table employee with empno, ename, designation and
salary.

CREATE TABLE employee (


empno int primary key,
ename varchar(20) NOT NULL,
designation varchar(20) NOT NULL,
salary int(20) NOT NULL);

-- 6. Write a query to display the column name and data type of the table employee

desc employee;

-- 7. Write a query to create a table from an existing table with all the fields.

CREATE TABLE employee2 AS


SELECT * FROM employee;

-- 8. Write a query to create table from an existing table with selected fields.

CREATE TABLE employee3 AS


SELECT ename, designation FROM employee;

-- 9. Write a query to create a new table from an existing table without any
record.

CREATE TABLE employee4 AS


SELECT * FROM employee WHERE 1=0;

-- 10. Write a query to Alter the column empno number(4) to empno number(6).

ALTER TABLE employee


MODIFY empno varchar(6);

-- 11. Write a query to Alter the table employee with multiple columns (empno,
ename).

ALTER TABLE employee


MODIFY {empno int(10),
ename varchar(50)};

-- 12. Write a query to add a new column in employee table.

ALTER TABLE employee


ADD DOJ date;

-- 13. Write a query to add multiple columns in employee table.

ALTER TABLE employee


ADD (
Qualification varchar(20),
DOB date
);

-- 14. Write a query to drop a column from an existing table employee.

ALTER TABLE employee


DROP COLUMN DOJ;
-- 15. Write a query to drop multiple columns from the employee table.

ALTER TABLE employee


DROP COLUMN Qualification,
DROP COLUMN DOB;

-- 16. Write a query to rename table employee to emp

ALTER TABLE employee


RENAME TO tableEmployee;

-- 1. Create a table employee with attributes emp_id, f_name, l_name, job_type,


salary, dept,commission, manager_id.

CREATE TABLE employee (


emp_id int(20),
f_name varchar(50),
l_name varchar(50),
job_type varchar(50),
salary int(20),
dept varchar(50),
commission char(20),
manager_id int(20)
);

-- 2. Make emp_id as the primary key of employee table.

ALTER TABLE employee


ADD CONSTRAINT pk_employees PRIMARY KEY (emp_id);

-- 3. Make f_name and salary NOT NULL type.

ALTER TABLE employee


MODIFY COLUMN f_name varchar(50) NOT NULL,
MODIFY COLUMN salary int(20) NOT NULL;

-- 4. Add a column date_of_joining in the employee table.

ALTER TABLE employee


ADD date_of_joining varchar(25);

-- 5. Create a table department with attribute d_name, d_loc and HOD_id where
d_name is primary key.

CREATE TABLE department (


d_name varchar(50) NOT NULL PRIMARY KEY,
d_loc varchar(50),
HOD_id int(20)
);

-- 6. Create a table location with attributes loc_id, city and contact_no.

CREATE TABLE location (


loc_id int(20) NOT NULL PRIMARY KEY,
city varchar(50),
contact_no int(20)
);
-- 7. Enhance the size of the ‘city’ attribute by 5, in the location table.

ALTER TABLE location


MODIFY city VARCHAR(55);

-- 8. Delete the contact_no attribute from the location table.

ALTER TABLE location


DROP COLUMN contact_no;

-- 9. Make the department attribute of the employee table its foreign key
referencing the department table.

ALTER TABLE employee


ADD CONSTRAINT FK_employee FOREIGN KEY (dept)
REFERENCES department(d_name);

-- 10. Rename the city attribute to ‘address’ in the location table.

ALTER TABLE location


RENAME COLUMN city TO address;

-- 11. Rename the location table name to ‘loc’.

ALTER TABLE location


RENAME TO loc;

12. Insert the following rows in ‘loc’ table

INSERT INTO loc


VALUES
(1, 'Kolkata'),
(2, 'Mumbai');

-- 13. Truncate the table ‘loc’.

TRUNCATE TABLE loc;

-- 14. Drop the table ‘loc’.

DROP TABLE loc;

-- 15. Insert the following rowsin the department table:

INSERT INTO department


VALUES
('Sales', 'Kol', 4),
('Accounts', 'Delhi', 6),
('Production', 'Kol', 1),
('Marketing', 'Kol', 2),
('R&D', 'Marketing', 8);

-- 16. Insert the following rows in the employee table:

INSERT INTO employee


VALUES
(1,'Arun','Khan','Manager',90000,NULL,'Production',NULL,'04-Jan-1998'),
(2,'Barun','Kumar','Manager',80000,NULL,'Marketing',NULL,'09-Feb-1998'),
(3,'Chitra','Kapoor','Engineer',60000,NULL,'Production',1,'08-Jan-1998'),
(4,'Dheeraj','Mishra','Manager',75000,NULL,'Sales',4,'27-Dec-2001'),
(5,'Emma','Dutt','Engineer',55000,NULL,'Production',1,'20-Mar-2002'),
(6,'Floki','Dutt','Accountant',70000,NULL,'Accounts',NULL,'16-Jul-2000'),
(7,'Dheeraj','Kumar','Clerk',40000,NULL,'Accounts',6,'01-Jul-2016'),
(8,'Saul','Good','Engineer',60000,NULL,'R&D',NULL,'06-Sep-2014'),
(9,'Mou','Bhat','Clerk',30000,NULL,'Sales',4,'08-Mar-2001'),
(10,'Sunny','Deol','Salesman',20000,10000,'Marketing',2,'31-Mar-2001'),
(11,'Bobby','Deol','Engineer',35000,NULL,'R&D',8,'17-Oct-2017'),
(12,'Aamir','Khan','Salesman',15000,5000,'Marketing',2,'11-Jan-2013');

-- 17. Show the values of departmental table.

SELECT * FROM department;

-- 18. Select the department names and their locations.

SELECT d_name, d_loc FROM department;

-- 19. Show the employees f_name , l_name , salary and the salary after 1000rs
Bonus.

SELECT f_name, l_name, salary, salary + 1000 AS salary_with_bonus FROM employee;

-- 20. Show the employees annual salary with a 1000rs. Yearly bonus and the annual
salary with a 100rs Monthly bonus.

SELECT f_name, l_name, salary, (salary * 12) + 1000 AS annual_salary_with_bonus,


(salary + 100) * 12 AS annual_salary_with_monthly_bonus FROM employee;

-- 21. Show f_name as NAME and annual salary as ANNSAL from the employee table.

SELECT f_name AS NAME, salary * 12 AS ANNSAL FROM employee;

-- 22. Show the l_name as LasT AND 100rs. Incremented salary as NewSal.

SELECT l_name AS LasT, salary + 100 AS NewSal FROM employee;

-- 23. Show the emp_id, f_name, l_name, job_type of the employee getting highest
salary.

SELECT emp_id, f_name, l_name, job_type FROM employee


WHERE salary = (SELECT MAX(salary) FROM employee);

-- 24. Show the emp_id, f_name, l_name, job_type of the employee getting minimum
salary.

SELECT emp_id, f_name, l_name, job_type FROM employee


WHERE salary = (SELECT MIN(salary) FROM employee);

-- 25. Show the average salary of employees in the employee table.

SELECT AVG(salary) AS average_salary FROM employee;

-- 26. Consider the Insurance database given below. The primary keys are underlined
and the data types are specified:

-- PERSON (driver-id: string, name: string, address: string)


-- CAR (Regno:string,model:string,year:int)
-- ACCIDENT (report-number:int,date:date,location:string)
-- OWNS (driver-id:string,regno:string)
-- PARTICIPATED (driver-id:string,regno:string,report-number:int,damage-amount:int)

-- i> Create the above tables by properly specifying the primary keys and the
foreign keys

CREATE TABLE person (


driver_id VARCHAR(50) PRIMARY KEY,
name VARCHAR(100),
address VARCHAR(200)
);

CREATE TABLE car (


regno VARCHAR(20) PRIMARY KEY,
model VARCHAR(100),
year INT
);

CREATE TABLE accident (


report_number INT PRIMARY KEY,
date DATE,
location VARCHAR(200)
);

CREATE TABLE owns (


driver_id VARCHAR(50),
regno VARCHAR(20),
PRIMARY KEY (driver_id, regno),
FOREIGN KEY (driver_id) REFERENCES person(driver_id),
FOREIGN KEY (regno) REFERENCES car(regno)
);

CREATE TABLE participated (


driver_id VARCHAR(50),
regno VARCHAR(20),
report_number INT,
damage_amount INT,
PRIMARY KEY (driver_id, regno, report_number),
FOREIGN KEY (driver_id) REFERENCES person(driver_id),
FOREIGN KEY (regno) REFERENCES car(regno),
FOREIGN KEY (report_number) REFERENCES accident(report_number)
);

-- ii> Enter atleast five tuples for each relation

INSERT INTO person


VALUES
('D1', 'John Doe', '123 Main St'),
('D2', 'Saul Goodman', '456 Elm St'),
('D3', 'Walter White', '789 Oak Ave'),
('D4', 'Jesse Pinkman', '101 Maple Rd'),
('D5', 'John Titor', '222 Pine Ln');

INSERT INTO car


VALUES
('ABC123', 'Swift Dzire', 2010),
('DEF456', 'Grand i10', 2006),
('GHI789', 'Ford Mustang', 2008),
('JKL012', 'Alto 800', 2008),
('MNO345', 'Indigo', 2011);

INSERT INTO accident


VALUES
(1, '2011-07-15', 'Intersection A'),
(12, '2006-08-05', 'Highway B'),
(3, '2010-06-20', 'Street C'),
(4, '2007-07-02', 'Road D'),
(5, '2013-08-10', 'Avenue E');

INSERT INTO owns


VALUES
('D1', 'ABC123'),
('D2', 'DEF456'),
('D3', 'GHI789'),
('D4', 'JKL012'),
('D5', 'MNO345');

INSERT INTO participated


VALUES
('D1', 'ABC123', 1, 5000),
('D2', 'DEF456', 12, 8000),
('D3', 'GHI789', 1, 3000),
('D4', 'JKL012', 3, 2000),
('D5', 'MNO345', 4, 6000);

-- iii> Demonstrate how you a. Update the damage amount for the car with a specific
regno in accident with report number 12 to 25000 b. Add a new accident to the
database

UPDATE participated
SET damage_amount = 25000
WHERE regno = 'DEF456' AND report_number = 12;

INSERT INTO accident (report_number, date, location)


VALUES (6, '2006-09-01', 'Street F');

-- iv> Find the total number of people who owned cars that were involved in
accidents in 2006.

SELECT COUNT(DISTINCT P.driver_id) AS total_people FROM PERSON P


JOIN OWNS O ON P.driver_id = O.driver_id
JOIN PARTICIPATED PT ON O.regno = PT.regno
JOIN ACCIDENT A ON PT.report_number = A.report_number
WHERE YEAR(A.date) = 2006;

-- v> Find the number of accidents in which cars belonging to a specific model were
involved.

SELECT COUNT(DISTINCT A.report_number) AS total_accidents FROM ACCIDENT A


JOIN PARTICIPATED PT ON A.report_number = PT.report_number
JOIN CAR C ON PT.regno = C.regno
WHERE C.model = 'Ford Mustang';

-- 1. Show f_name, l_name and job_type from employees.

SELECT f_name, l_name, job_type FROM employee;


-- 2. Show employee details in the following fashion:

SELECT CONCAT(f_name, ' is a ', job_type) AS Employee_Details FROM employee;

-- 3. Show the monthly salary details in the following fashion

SELECT CONCAT(f_name, '''s monthly salary is Rs ', salary) AS


Monthly_Salary_Details FROM employee;

-- 4. Show the different department names from department table.

SELECT d_name FROM department;

-- 5. Show the employee names who works in ‘Sales’.

SELECT f_name FROM employee


WHERE dept = 'Sales';

-- 6. Show the employee names who gets salary of more than 50000 per month.

SELECT f_name FROM employee


WHERE salary > 50000;

-- 7. Show the details of the employee whose manager id is not 1.

SELECT *FROM employee


WHERE manager_id != 1 OR manager_id IS NULL;

-- 8. Show the employee details whose salary ranges between 40000 and 70000.

SELECT *FROM employee


WHERE Salary BETWEEN 40000 AND 70000;

-- 9. Show the details of the employees who works under the manager having id 1, 6
and 8.

SELECT *FROM employee


WHERE manager_id IN (1, 6, 8);

-- 10. Select the f_name and salary of those employees whose last name starts with
‘K’.

SELECT f_name, salary FROM employee


WHERE l_name LIKE 'K%';

-- 11. Select the f_name and salary of those employees whose last name starts with
‘K’ and ends with ‘R’.

SELECT f_name, salary FROM employee


WHERE l_name LIKE 'K%R';

-- 12. Show the details of those employees where 3rd letter of l_name is ‘o’.

SELECT *FROM employee


WHERE l_name LIKE '__o%';

-- 13. Select the details of those employees who works as an engineer with monthly
salary more than 50000.
SELECT *FROM employee
WHERE job_type = 'Engineer' AND salary > 50000;

-- 14. Select the employees whose department is ‘Production’ or monthly salary is


more than 60000 per month.

SELECT *FROM employee


WHERE dept = 'Production' OR salary > 60000;

-- 15. Find the minimum salary, maximum salary, total salary, average salary of the
employees who work in ‘Sales’ department.

SELECT MIN(salary) AS minimum_salary, MAX(salary) AS maximum_salary, SUM(salary) AS


total_salary, AVG(salary) AS average_salary FROM employee
WHERE dept = 'Sales';

-- 16. Find the employee l_name that is first and f_name that is last if they are
arranged in an order

SELECT l_name, f_name FROM employee ORDER BY l_name ASC, f_name DESC;

-- 17. Find the number of employees working in each department

SELECT dept, COUNT(*) FROM employee GROUP BY dept;

-- 18. Find the number of departments from employee table

SELECT COUNT(DISTINCT dept) AS number_of_departments FROM employee;

-- 19. Find the average commission of the employees.

SELECT AVG(commission) AS average_commission FROM employee;

-- 20. Find the average salaries of the employees department wise

SELECT DISTINCT dept, AVG(salary) AS average_salary FROM employee GROUP BY dept;

-- 21. Find the sum of salary of different job_type according to different


departments

SELECT DISTINCT dept, job_type, SUM(salary) AS total_salary FROM employee GROUP BY


dept, job_type;

-- 22. Find the department name and average salaries of those departments whose
average salary is greater than 40000

SELECT DISTINCT dept, AVG(salary) AS average_salary FROM employee GROUP BY dept


HAVING AVG(salary) > 40000;

-- 23. Find the department name and maximum salaries of those departments whose
maximum salary is greater than 55000

SELECT DISTINCT dept, MAX(salary) AS maximum_salary FROM employee GROUP BY dept


HAVING MAX(salary) > 55000;

-- 24. Display the job_type and total monthly salary for each job_type where total
payroll is exceeding 100000

SELECT DISTINCT job_type, SUM(salary) AS Total_salary FROM employee GROUP BY


job_type HAVING SUM(salary) > 100000;

-- 25. Display the name of the department having maximum average salary.

SELECT dept FROM employee GROUP BY dept


HAVING AVG(salary) = (SELECT AVG(salary) FROM employee
GROUP BY dept ORDER BY AVG(salary) DESC
LIMIT 1);

-- 1. Show the use of upper and lower function.

SELECT UPPER('hello world!'), LOWER('HELLO WORLD!');

-- 2. Show the use of concat, instr and length function

SELECT CONCAT('Hello' , 'world') FROM DUAL;

SELECT INSTR('Hello World', 'r') FROM DUAL;

SELECT LENGTH('Hello world!') FROM DUAL;

-- 3. Show the use of the following functions on numeric values:

-- a. Sqrt()

SELECT sqrt(25) FROM DUAL;

-- b. Power()

SELECT POWER(5,2) FROM DUAL;

-- c. Ceil()

SELECT CEIL(12.534) FROM DUAL;

-- d. Substr()

SELECT SUBSTR('Hellow World', 3, 3) FROM DUAL;

-- e. Max()

SELECT MAX(salary) FROM employee;

-- f. min()

SELECT MIN(salary) FROM employee;

-- g. Round()

SELECT ROUND(24.674) FROM DUAL;

-- h. avg()

SELECT AVG(salary) FROM employee;

-- i. count()

SELECT COUNT(dept) FROM employee;


-- j. Exp()

SELECT EXP(5) FROM DUAL;

-- k. mod()

SELECT MOD(8, 4) FROM DUAL;

-- 4. Solve the following queries

-- a. Find the ceiling and floor value of 14.887.

SELECT CEIL(14.887), FLOOR(14.887) FROM DUAL;

-- b. Find out the round-off 17.49989.

SELECT ROUND(17.49989) FROM DUAL;

-- c. Calculate 8^7.

SELECT POWER(8, 7) FROM DUAL;

-- 5. Show the current date.

SELECT DATE_FORMAT(NOW(), '%Y/%d/%m') AS Todays_Date;

-> use 'SYSDATE' instead of 'NOW()' if u are doing it in oracle !

-- 6. Find the total experience of the employees in weeks who works in Sales
department.

SELECT f_name , l_name , ROUND(DATEDIFF(NOW(), date_of_joining) / 7) AS


Experience_in_weeks FROM employee
WHERE dept = 'Sales';

-> FOR ORACLE SQL use

SELECT f_name, l_name, ROUND(MONTHS_BETWEEN(SYSDATE, date_of_joining) / 7) AS


total_experience_in_weeks FROM employee
WHERE dept = 'Sales';

-- From this point Onwards nothing will work in MYSQL and can only be done in
ORACLE --

-- 7. Display the use of the following functions on date

-- a. Months_between

SELECT MONTHS_BETWEEN(TO_DATE('2023-12-25', 'YYYY-MM-DD'), TO_DATE('2023-01-25',


'YYYY-MM-DD')) AS months_between FROM DUAL;

-- b. Add_months

SELECT ADD_MONTHS(TO_DATE('2023-01-25', 'YYYY-MM-DD'), 6) AS add_months FROM DUAL;

-- c. Next_day
SELECT NEXT_DAY(TO_DATE('2023-01-25', 'YYYY-MM-DD'), 'TUESDAY') AS next_day FROM
DUAL;

-- d. Last_day

SELECT LAST_DAY(TO_DATE('2023-01-25', 'YYYY-MM-DD')) AS last_day FROM DUAL;

-- e. Round

SELECT ROUND(TO_DATE('2023-01-25 5:36:55', 'YYYY-MM-DD HH:MI:SS'), 'HH') AS


round_time FROM DUAL;

-- f. Trunc

SELECT TRUNC(TO_DATE('2023-01-25 5:36:55', 'YYYY-MM-DD HH:MI:SS'), 'MM') AS


trunc_date FROM DUAL;

-- g. To_char

SELECT TO_CHAR(TO_DATE('2023-01-25', 'YYYY-MM-DD'), 'Month DD - YYYY') AS to_char


FROM DUAL;

-- From this point Onwards it will work in MYSQL too --

-- 8. Show the employee details with a revised salary. The salary is incremented in
the following way:

UPDATE employee SET salary = CASE


WHEN dept = 'Sales' THEN salary * 0.1
WHEN dept = 'Marketing' THEN salary * 0.2
ELSE salary * 1
END;

-- 9. Determine the tax for each employee in production department based on the
monthly salary. The tax rate are as per the following data:

SELECT emp_id, f_name, salary, dept,


CASE
WHEN salary BETWEEN 0 AND 19999 THEN 0
WHEN salary BETWEEN 20000 AND 39999 THEN salary * 0.09
WHEN salary BETWEEN 40000 AND 59999 THEN salary * 0.2
WHEN salary BETWEEN 60000 AND 79999 THEN salary * 0.3
ELSE salary * 0.45
END AS tax
FROM employee WHERE dept = 'Production';

-- 10. Find the Cartesian product between Employee and Department table.

SELECT *FROM Employee


CROSS JOIN Department;

-- 11. Show the employee names and the respective department location.

SELECT employee.f_name, employee.l_name, department.d_loc FROM employee


JOIN department ON employee.dept = department.d_name;

-- 12. Give an example of the following joins considering employee and department
tables.

--k. Natural join

SELECT *FROM employee


NATURAL JOIN department;

-- l. Inner join

SELECT *FROM employee


INNER JOIN department ON employee.dept = department.d_name;

-- m. Left outer join

SELECT *FROM employee


LEFT OUTER JOIN department ON employee.dept = department.d_name;

-- n. Right outer join

SELECT *FROM employee


RIGHT OUTER JOIN department ON employee.dept = department.d_name;

-- o. Full outer join

-- FOR MYSQL -

SELECT *FROM employee


LEFT OUTER JOIN department ON employee.dept = department.d_name
UNION
SELECT *FROM employee
RIGHT OUTER JOIN department ON employee.dept = department.d_name;

-- FOR ORACLE SQL -

SELECT *FROM employee


FULL OUTER JOIN department ON employee.dept = department.d_name;

-- 13. Write a query to find the address.

SELECT locations.location_id, locations.street_address, locations.city,


locations.state_province, countries.country_name FROM locations
NATURAL JOIN countries
LIMIT 0, 25;

-- 14. Write a query to find the name. -> incomplete QS

SELECT employees.first_name, employees.last_name, departments.department_id FROM


employees
JOIN departments ON employees.employee_id = departments.deparment_id;

-- 1. Find the Cartesian product between Employee and Department table.

SELECT *FROM Employee


CROSS JOIN Department;

-- 2. Show the employee names and the respective department location.


SELECT employee.f_name, employee.l_name, department.d_loc FROM employee
JOIN department ON employee.dept = department.d_name;

-- 3. Find the employee name and date of joining who are working in Delhi.

SELECT employee.f_name, employee.l_name, employee.date_of_joining FROM employee


JOIN department ON employee.dept = department.d_name
WHERE department.d_loc = 'Delhi';

-- 4. Create a table ‘Emp_Address’ for storing the permanent address of the


employees and insert the following values:

CREATE TABLE Emp_Address(


Emp_id int(20),
City varchar(20),
District varchar(20),
State varchar(20)
);

INSERT INTO Emp_Address


VALUES
(1,'Suri','Birbhum','WB'),
(2,'Kolkata','Kolkata','WB'),
(3,'Bhubaneswar','Khurda','Odisha'),
(4,'Durgapur','Burdwan','WB'),
(5,'Noida','GB Nagar','UP'),
(6,'Secunderabad','Hyderabad','Telangana'),
(7,'Derhadun','Dehradun','Uttarakhand'),
(8,'Asansol','Burdwan','WB'),
(9,'Siliguri','Darjeeling','WB'),
(10,'Kolkata','Kolkata','WB'),
(11,'Jalpaiguri','Jalpaiguri','WB'),
(12,'New Delhi','New Delhi','Delhi');

-- 5. Display the name of employees, department location and the city name the
employee belongs to, from the Employee, Department and Emp_Address tables.

SELECT employee.f_name, employee.l_name, department.d_loc, Emp_Address.City FROM


employee
JOIN department ON employee.dept = department.d_name
JOIN Emp_Address ON Emp_Address.Emp_id = employee.emp_id;

-- 6. Find the name of each department’s manager.

SELECT f_name, l_name, dept FROM employee


WHERE job_type = 'Manager';

-- 7. Create ‘Job_Grades’ table and insert the following values:

CREATE TABLE Job_Grades(


GRADE char(10),
LOWEST_SAL int(10),
HIGHEST_SAL int(30)
);

INSERT INTO Job_Grades


VALUES
('A',10000,24999),
('B',25000,49999),
('C',50000,100000);

-- 8. Display the employee names with their respective job grades and salary.

SELECT f_name, salary,


CASE
WHEN salary BETWEEN 10000 AND 24999 THEN 'A'
WHEN salary BETWEEN 25000 AND 49999 THEN 'B'
WHEN salary BETWEEN 50000 AND 100000 THEN 'C'
END AS Job_Grades
FROM employee;

-- 9. Insert two rows in Employee table having ‘NULL’ values in dept field.

INSERT INTO employee


VALUES
(13,'Raj','Chatterjee','Mechanic',20000,5000,NULL,3,'08-Dec-2005'),
(14,'Rahul','Khan','Electrician',40000,2000,NULL,5,'12-Aug-1984');

-- 10. Insert two rows in Department table.

INSERT INTO department


VALUES
('Mechanic', 'Kol', 3),
('Electric', 'Delhi', 5);

-- 11. Perform the following joins considering Employee and Department tables.

-- a. Natural join

SELECT *FROM employee


NATURAL JOIN department;

-- b. Inner join

SELECT *FROM employee


INNER JOIN department ON employee.dept = department.d_name;

-- c. Left outer join

SELECT *FROM employee


LEFT OUTER JOIN department ON employee.dept = department.d_name;

-- d. Right outer join

SELECT *FROM employee


RIGHT OUTER JOIN department ON employee.dept = department.d_name;

-- e. Full outer join

-- FOR MYSQL -

SELECT *FROM employee


LEFT OUTER JOIN department ON employee.dept = department.d_name
UNION
SELECT *FROM employee
RIGHT OUTER JOIN department ON employee.dept = department.d_name;
-- FOR ORACLE SQL -

SELECT *FROM employee


FULL OUTER JOIN department ON employee.dept = department.d_name;

-- 1. Write An SQL Query To Fetch “FIRST_NAME” From Worker Table In Upper Case
alias as WORKER_FIRSTNAME.

SELECT UPPER(FIRST_NAME) AS WORKER_FIRSTNAME FROM Worker;

-- 2. Write An SQL Query To Print The First Three Characters Of FIRST_NAME From
Worker Table.

SELECT SUBSTRING(FIRST_NAME, 1, 3) AS First3 FROM Worker;

-- 3. Write An SQL Query To Find The Position Of The Alphabet (‘A’) In The First
Name Column ‘Amitabh’ From Worker Table.

SELECT INSTR(FIRST_NAME, 'A') AS Position_of_A FROM Worker


WHERE FIRST_NAME = 'Amitabh';

-- 4. 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;

-- 5. Write An SQL Query To Print All Worker Details From The Worker Table Order By
FIRST_NAME Ascending And DEPARTMENT Descending.

SELECT *FROM Worker ORDER BY FIRST_NAME ASC, DEPARTMENT DESC;

-- 6. Write An SQL Query To Print Details Of The Workers Whose FIRST_NAME Contains
‘A’.

SELECT *FROM Worker


WHERE FIRST_NAME LIKE '%A%';

-- 7. Write An SQL Query To Print Details Of The Workers Whose FIRST_NAME Ends With
‘A’.

SELECT *FROM Worker


WHERE FIRST_NAME LIKE '%A';

-- 8. Write An SQL Query To Print Details Of The Workers Whose SALARY Lies Between
100000 And 500000.

SELECT *FROM Worker


WHERE SALARY BETWEEN 100000 AND 500000;

-- 9. Write An SQL Query To Fetch The Count Of Employees Working In The Department
‘Admin’.

SELECT COUNT(FIRST_NAME) AS NO_OF_EMPLOYEE, DEPARTMENT FROM Worker


WHERE DEPARTMENT = 'Admin'
GROUP BY DEPARTMENT;

-- 10. Write An SQL Query To Fetch The No. Of Workers For Each Department In The
Descending Order.
SELECT COUNT(*) AS NO_OF_EMPLOYEE, DEPARTMENT FROM Worker
GROUP BY DEPARTMENT
ORDER BY NO_OF_EMPLOYEE DESC;

-- 11. Write An SQL Query To Print Details Of The Workers Who Are Also Managers.

SELECT Worker.* FROM Worker


JOIN Title ON Title.WORKER_REF_ID = Worker.WORKER_ID
WHERE Title.WORKER_TITLE = 'Manager';

-- 12. Write An SQL Query To Show Only Odd Rows From A Table.

SELECT *FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY WORKER_ID) AS row_num FROM


Worker) AS numbered_rows
WHERE row_num % 2 != 0;

-- 13. Write An SQL Query To Show Records From One Table That Another Table Does
Not Have.

SELECT * FROM worker


LEFT JOIN bonus ON worker.worker_id = bonus.worker_ref_id
WHERE bonus.worker_ref_id IS NULL;

-- 14. Write An SQL Query To Show The Top N (Say 10) Records Of A Table.

SELECT *FROM Worker -- For MYSQL


LIMIT 10;

SELECT TOP 10 *FROM Worker; -- For ORACLE

-- 15. Write An SQL Query To Fetch The List Of Employees With The Same Salary.

SELECT first_name,salary FROM worker


WHERE Salary IN (SELECT Salary FROM worker GROUP BY Salary HAVING COUNT(*) > 1);

-- 16. Write An SQL Query To Show All Departments Along With The Number Of People
Working There.

SELECT DEPARTMENT, COUNT(*) AS NO_OF_EMPLOYEE FROM Worker GROUP BY DEPARTMENT;

-- 17. Write An SQL Query To Print The Name Of Employees Having The Highest Salary
In Each Department.

SELECT department, first_name, salary FROM ( SELECT department, first_name, salary,


ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS rn FROM worker)
ranked;

-- 18. Write An SQL Query To Fetch Departments Along With The Total Salaries Paid
For Each Of Them.

SELECT DEPARTMENT, SUM(SALARY) FROM Worker GROUP BY DEPARTMENT;

-- 19. Consider the following relations for an order processing database


application in a company.

-- i) Create the above tables by properly specifying the primary keys and the
foreign keys.
CREATE TABLE CUSTOMER(
Cust int(25) NOT NULL PRIMARY KEY,
Cname char(25),
City char(25)
);

CREATE TABLE ORDERR(


Orderr int(25) NOT NULL PRIMARY KEY,
Odate date,
Cust int(25),
Ord_Amt int(25),
FOREIGN KEY (Cust) REFERENCES CUSTOMER(Cust)
);

CREATE TABLE ORDERR_ITEM(


Orderr int(25) NOT NULL PRIMARY KEY,
Item int(25),
qty int(25)
);

CREATE TABLE ITEM(


Item int(25),
Unit_Price int(25)
);

CREATE TABLE SHIPMENT(


Orderr int(25),
Warehouse int(25) NOT NULL PRIMARY KEY,
Ship_Date date
);

CREATE TABLE WAREHOUSE(


Warehouse int(25),
City char(25),
FOREIGN KEY (Warehouse) REFERENCES SHIPMENT(Warehouse)
);

-- ii) Enter at least five tuples for each relation.

INSERT INTO CUSTOMER


VALUES
(234, 'Jake', 'Kolkata'),
(345, 'Paul', 'Varanashi'),
(626, 'Robie', 'Noida'),
(328, 'Mischel', 'Delhi'),
(457, 'Marie', 'Jadavpur');

INSERT INTO ORDERR


VALUES
(100, '2023-06-13', 234, 5600),
(101, '2023-01-04', 345, 45673),
(102, '2023-02-24', 626, 9564),
(103, '2023-05-27', 328, 3563),
(104, '2023-07-09', 457, 8543);

INSERT INTO ORDERR_ITEM


VALUES
(100, 10, 12),
(101, 11, 34),
(102, 12, 56),
(103, 13, 76),
(104, 14, 36);

INSERT INTO ITEM


VALUES
(10, 25000),
(11, 45000),
(12, 35000),
(13, 15000),
(14, 75000);

INSERT INTO SHIPMENT


VALUES
(100, 3546, '2023-01-16'),
(101, 7546, '2023-04-02'),
(102, 2453, '2023-01-20'),
(103, 6432, '2023-06-11'),
(104, 2423, '2023-07-09');

INSERT INTO WAREHOUSE


VALUES
(3546, 'kolkata'),
(7546, 'Varanashi'),
(2453, 'Noida'),
(6432, 'Delhi'),
(2423, 'Jadavpur');

-- iii) Produce a listing: CUSTNAME, NO_OF_ORDERS, AVG_ORDER_AMT, where the middle


column is the total number of orders by the customer and the last column is the
average order amount for that customer

SELECT CUSTOMER.Cname AS CUSTNAME, COUNT(ORDERR.Orderr) AS NO_OF_ORDERS,


AVG(ORDERR.Ord_Amt) AS AVG_ORDER_AMT FROM ORDERR
JOIN CUSTOMER ON CUSTOMER.Cust = ORDERR.Cust
GROUP BY CUSTNAME;

-- iv) List the Order# for the orders that were shipped from all the warehouses
that the company has in a specific city

SELECT Orderr AS Order_id FROM SHIPMENT


JOIN Warehouse ON WAREHOUSE.Warehouse = SHIPMENT.Warehouse
WHERE City = 'Kolkata';

-- v) Demonstrate how you delete Item# 10 from the ITEM table and make that field
null in the ORDER- ITEM table.

DELETE FROM ITEM WHERE Item = 10;


UPDATE ORDERR_ITEM SET Item = NULL WHERE Item = 10;

-- 20. Create a table Emp(e_no, e_name, e_phone, e_addr,e_salary) to store records


of 10 employees:

-- i) Alter the data type of e_no from number to varchar

ALTER TABLE Emp


MODIFY e_no VARCHAR(50);

-- ii) Alter table by setting e_no as primary key


ALTER TABLE Emp
ADD CONSTRAINT PK PRIMARY KEY (e_no);

-- iii) Alter table by adding a column e_pin

ALTER TABLE Emp


ADD e_pin VARCHAR(25);

-- iv) Update the phone number of an employee in the table

UPDATE Emp
SET e_phone = '86487988'
WHERE e_no = '5';

-- 21. Create a table Dept(dept_no, dept_name,e_no, dept_loc,dept_hod) to store


records of 10 departments:

-- i) Create the reference between Emp and Dept table with e_no attribute.

ALTER TABLE Dept


ADD CONSTRAINT FK FOREIGN KEY (e_no) REFERENCES Emp(e_no);

-- ii) Assign dept_no as primary key.

ALTER TABLE Dept


ADD CONSTRAINT PK PRIMARY KEY (dept_no);

-- iii) Update the dept_hod for one department.

UPDATE Dept
SET dept_hod = 'Rajju'
WHERE dept_no = '20';

-- iv) Delete one department

DELETE FROM Dept


WHERE dept_no = '20';

-- 22. Solve the following queries

-- i) Write a query to find the employee name and dept_hod whose dept_hod is SAY,
“John”.

SELECT emp.e_name AS EmployeeName, dept.dept_hod FROM emp


JOIN Dept ON emp.e_no = dept.e_no
WHERE dept_hod = 'Rajdip';

-- ii) Write a query to find the average salary of the employee of CSE department.

SELECT AVG(emp.e_salary) AS average_salary FROM emp


JOIN Dept ON emp.e_no = dept.e_no
WHERE dept_name = 'CSE';

-- 1. Create Job_History table and insert the following data.

CREATE TABLE Job_History(


Emp_id int(2),
Start_date varchar(25),
End_date varchar(25),
Job_type char(25),
D_name varchar(25)
);

INSERT INTO Job_History


VALUES
(1,'04-Jan-1998','30-Jun-2001','Engineer','Production'),
(2,'09-Feb-1998','28-Feb-2002','Salesman','Sales'),
(1,'01-Jul-2001','31-Dec-2010','Manager','R&D'),
(4,'27-Dec-2001','19-Sep-2016','Sales_Executive','Marketing'),
(2,'01-Mar-2002','30-Mar-2015','Sales_Executive','Marketing'),
(2,'01-Apr-2016','15-Dec-2017','Manager','Sales'),
(4,'20-Sep-2016','16-Dec-2017','ASST Manager','Sales'),
(6,'16-Jul-2000','30-Nov-2006','Clerk','Accounts'),
(5,'20-Mar-2002','12-Aug-2011','Engineer','R&D'),
(1,'01-Jan-2011','31-Jan-2012','Engineer','Production');

-- 2. Display the previous and current job_types of all the employees.

SELECT employee.F_name, employee.job_type AS PrevJob, Job_History.job_type CurrJob


FROM employee
JOIN job_history ON employee.Emp_id = Job_History.Emp_id;

-- 3. Display the previous and current department and job_types of all the
employees.

SELECT employee.F_name, employee.dept AS PrevDept, Job_History.D_name AS CurrDept,


Job_History.job_type FROM employee
JOIN job_history ON employee.Emp_id = Job_History.Emp_id;

-- 4. Display the employee id and job_types of the employees who currently have a
job title that they held previously.

SELECT employee.Emp_id, Job_history.job_type FROM employee


JOIN job_history ON employee.Emp_id = Job_History.Emp_id
WHERE employee.job_type = Job_History.job_type;

-- 5. Find the name of those employees who have not changed their jobs once.

SELECT CONCAT(employee.F_name, ' ' , employee.L_name) AS NameOfEmployee FROM


employee
JOIN job_history ON employee.Emp_id = Job_History.Emp_id
WHERE employee.job_type = Job_History.job_type;

-- 6. Find the names of the employees who earn more than Chitra.

SELECT CONCAT(F_name, ' ', L_name) AS NameOfEmployee FROM employee


WHERE salary > (SELECT salary FROM employee WHERE F_name = 'Chitra');

-- 7. Find the details of those employees who have the same job_type as of emp_id
7.

SELECT *FROM employee


WHERE job_type = (SELECT job_type FROM employee WHERE Emp_id = 7);

-- 8. Find the details of the employees whose job_type is same as that of emp_id 3
and whose salary is greater than that of emp_id 7.
SELECT *FROM employee
WHERE job_type = (SELECT job_type FROM employee WHERE Emp_id = 3) AND salary >
(SELECT salary FROM employee WHERE Emp_id = 7);

-- 9. Display l_name, job_type and the salary of the employees whose salary is
equal to the minimum salary.

SELECT L_name, job_type, salary FROM employee


WHERE salary = (SELECT MIN(salary) FROM employee);

-- 10. Find the job_type with lowest average salary.

SELECT job_type, AVG(salary) AS average_salary FROM employee


GROUP BY job_type
ORDER BY average_salary ASC
LIMIT 1;

-- 11. Display all the departments that have a minimum salary greater than that of
‘Sales’ department.

SELECT dept FROM employee GROUP BY dept


HAVING MIN(salary) > (SELECT MIN(salary) FROM employee WHERE dept = 'Sales');

-- 12. Find the employees who earn the same salary for each department.

SELECT d_name
FROM Department
WHERE (SELECT MIN(salary) FROM employee WHERE job_type = 'Sales') < ALL
(SELECT MIN(salary) FROM employee WHERE job_type = Department.d_name)
GROUP BY d_name;

-- 13. Display the employees who are not engineers and whose salary is less than
that of any engineer.

SELECT CONCAT(F_name, ' ', L_name) AS NameOfEmployee FROM employee


WHERE job_type != 'Engineer' AND salary < (SELECT MIN(salary) FROM employee WHERE
job_type = 'Engineer');

-- 14. Display the employees whose salary is less than the salary of all employees
with a job_type ‘Clerk’ and whose job_type is not ‘Clerk’.

SELECT CONCAT(F_name, ' ', L_name) AS NameOfEmployee FROM employee


WHERE salary < (SELECT MIN(salary) FROM employee WHERE job_type = 'Clerk') AND
job_type != 'Clerk';

-- 15. Consider the following database of students enrollment in courses and books
adopted for each course.

-- STUDENT(regno: string, name: string, major: strong, bdate: date)


-- COURSE(course-no: int cname: string, dept: string)
-- ENROLL(reg-no: string, course-no: int, sem: int, marks: int)
-- BOOK-ADOPTION(course-no: int, sem: int, book-isbn: int)
-- TEXT(book-isbn: int, book-title: string, publisher: string, author: string)

-- i) Create the above tables by properly specifying the primary keys and the
foreign keys

CREATE TABLE STUDENT(


regno char(25),
name char(25),
major char(25),
bdate date
);

CREATE TABLE COURSE(


course_no int(25),
cname char(25),
dept char(25)
);

CREATE TABLE ENROLL(


reg_no char(25),
course_no int(25),
sem int(25),
marks int(25)
);

CREATE TABLE BOOK_ADOPTION(


course_no int(25),
sem int(25),
book_isbn int(25)
);

CREATE TABLE TEXT(


book_isbn int(25),
book_title char(25),
publisher char(25),
author char(25)
);

-- ii) Enter atleast five tuples for each relation.

INSERT INTO STUDENT


VALUES
(10000, 'Paul', 'UG', '2023-07-24'),
(10001, 'Deol', 'PG', '2023-06-28'),
(10002, 'Adin', 'UG', '2023-06-09'),
(10003, 'Andrew', 'PG', '2023-08-07'),
(10004, 'Devin', 'UG', '2023-09-28');

INSERT INTO COURSE


VALUES
(501, 'BTech', 'CSE'),
(402, 'BTech', 'CSE(IOT)'),
(603, 'BTech', 'ME'),
(805, 'BTech', 'ECE'),
(107, 'BTech', 'CSIT');

INSERT INTO ENROLL


VALUES
('ABC', 501, 2, 85),
('DEF', 402, 4, 67),
('GHI', 603, 5, 98),
('JKL', 805, 1, 56),
('MNO', 107, 6, 66);

INSERT INTO BOOK_ADOPTION


VALUES
(501, 2, 2501),
(402, 4, 2521),
(603, 5, 2551),
(805, 1, 2351),
(107, 6, 2751);

INSERT INTO TEXT


VALUES
(2501, 'The Android Odyssey', 'R. A. Townsend Co', 'Paula'),
(2521, 'The Unseen Threat', 'Great Woods Family Dentistry', 'Edward'),
(2551, 'The Sorcerer Apprentice', 'Florida Sports Magazine', 'Kenway'),
(2351, 'The Joy of Simplicity', 'Texas Section Of The Institute Of Transportation
E', 'Tate'),
(2751, 'Unraveled Mysteries', 'Com Media Llc', 'Randy');

-- iii) Demonstrate how you add a new text book to the database and make this book
be adopted by some department.

-- Step 1: Insert the new textbook information into the "TEXT" table
INSERT INTO TEXT (book_isbn, book_title, publisher, author)
VALUES (2754, 'Exploring Mysteries', 'Knowledge World', 'Sophia');

-- Step 2: Insert the adoption information into the "BOOK_ADOPTION" table


INSERT INTO BOOK_ADOPTION (course_no, sem, book_isbn)
VALUES (501, 2, 2754);

-- iv) Produce a list of text books (include Course-no, book-isbn, book-title) in


the alphabetical order for courses offered by the ‘Compute Science’ department that
use more than two books.

INSERT INTO COURSE


VALUES
(401, 'Computer Networks', 'CSE'),
(402, 'Internet of Things', 'CSE');

INSERT INTO BOOK_ADOPTION


VALUES
(401, 1, 2751),
(401, 1, 2752),
(401, 1, 2753),
(402, 2, 2752),
(402, 2, 2753);

SELECT BA.course_no, BA.book_isbn, T.book_title


FROM BOOK_ADOPTION BA
JOIN TEXT T ON BA.book_isbn = T.book_isbn
JOIN COURSE C ON BA.course_no = C.course_no
WHERE C.dept = 'CSE'
GROUP BY BA.course_no, BA.book_isbn, T.book_title
HAVING COUNT(*) > 2
ORDER BY T.book_title;

-- v) List any department that has all its adopted books published by a specific
publisher.

INSERT INTO COURSE


VALUES
(701, 'Data Science', 'Computer Science');

INSERT INTO BOOK_ADOPTION


VALUES
(701, 1, 2752);

INSERT INTO BOOK_ADOPTION


VALUES
(701, 1, 2753);

SELECT BA.course_no, C.dept


FROM BOOK_ADOPTION BA
JOIN TEXT T ON BA.book_isbn = T.book_isbn
JOIN COURSE C ON BA.course_no = C.course_no
WHERE T.publisher = 'Wonderful Press'
GROUP BY BA.course_no, C.dept
HAVING COUNT(*) = (SELECT COUNT(*) FROM BOOK_ADOPTION WHERE course_no =
BA.course_no);

-- 1. The following tables are maintained by a book dealer


-- AUTHOR(author-id: int, name: string, city: string, country: string)
-- PUBLISHER(publisher-id: int name: string, city: string, country: string)
-- CATLOG(book-id: int, title : string, author-id: int, publisher-id: int,
category: int, year:
-- int, price: int)
-- CATEGORY(category-id: int, description: string)
-- ORDER-DETAILS(order-no: int, book-id: int, quantity: int)

-- i) Create above tables by properly specifying the primary keys and the foreign
keys.

CREATE TABLE author (


author_id INT(25),
author_name VARCHAR(25),
author_city VARCHAR(25),
author_country VARCHAR(25),
PRIMARY KEY(author_id)
);

CREATE TABLE publisher (


publisher_id INT(25),
publisher_name VARCHAR(25),
publisher_city VARCHAR(25),
publisher_country VARCHAR(25),
PRIMARY KEY (publisher_id)
);

CREATE TABLE category (


category_id INT(25),
description VARCHAR(25),
PRIMARY KEY (category_id) );

CREATE TABLE catalogue(


book_id INT(25),
book_title VARCHAR(25),
author_id INT(25),
publisher_id INT(25),
category_id INT(25),
year INT(25),
price INT(25),
PRIMARY KEY (book_id),
FOREIGN KEY (author_id) REFERENCES author(author_id),
FOREIGN KEY (publisher_id) REFERENCES publisher(publisher_id),
FOREIGN KEY (category_id) REFERENCES category(category_id));

CREATE TABLE orderdetails(


order_id INT(25),
book_id INT(25),
quantity INT(25),
PRIMARY KEY (order_id),
FOREIGN KEY (book_id) REFERENCES catalogue(book_id));

-- ii) Enter atleast five tuples for each relation.

INSERT INTO author


VALUES
(1001,'JK Rowling','London','England'),
(1002,'Chetan Bhagat','Mumbai','India'),
(1003,'John McCarthy','Chicago','USA'),
(1004,'Dan Brown','California','USA'),
(1005,'Ana Huang','New york','USA');

INSERT INTO publisher


VALUES
(2001,'Bloomsbury','London','England'),
(2002,'Scholastic','Washington','USA'),
(2003,'Pearson','London','England'),
(2004,'Rupa','Delhi','India') ,
(2005,'MC Graw Hill','New York','USA');

INSERT INTO category


VALUES
(3001,'Fiction'),
(3002,'Non-Fiction'),
(3003,'thriller'),
(3004,'action'),
(3005,'fiction');

INSERT INTO catalogue


VALUES
(4001,'HP and Goblet Of Fire',1001,2001,3001,2002,600),
(4002,'HP and Order Of Phoenix',1001,2002,3001,2005,650),
(4003,'Two States',1002,2004,3001,2009,65),
(4004,'3 Mistakes of my life',1002,2004,3001,2007,55),
(4005,'Da Vinci Code',1004,2003,3001,2004,450),
(4006,'Angels and Demons',1004,2003,3001,2003,350),
(4007,'Artificial Intelligence',1003,2002,3002,1970,500);

INSERT INTO orderdetails


VALUES
(5001,4001,5),
(5002,4002,7),
(5003,4003,15),
(5004,4004,11),
(5005,4005,9),
(5006,4006,8),
(5007,4007,2),
(5008,4004,3);

-- iii) Give the details of the authors who have 2 or more books in the catalog and
the price of the books is greater than the average price of the books in the
catalog and the year of publication is after 2010.

SELECT A.author_name, B.book_title, B.Price, B.Year


FROM Author A
JOIN Catalogue B ON A.author_id = B.author_id
WHERE B.Year > 2001
AND A.author_id IN (
SELECT A1.author_id
FROM Author A1
JOIN Catalogue B1 ON A1.author_id = B1.author_id
GROUP BY A1.author_id, A1.author_name
HAVING COUNT(B1.book_id) >= 2
AND AVG(B1.Price) < (
SELECT AVG(Price) FROM Catalogue
)
);

-- iv) Find the author of the book which has maximum sales.

--For Oracle

WITH AuthorSales AS (
SELECT C.author_id, SUM(O.quantity) AS total_sales
FROM catalogue C
JOIN orderdetails O ON C.book_id = O.book_id
GROUP BY C.author_id
ORDER BY SUM(O.quantity) DESC
)
SELECT A.author_id, A.author_name
FROM author A
JOIN AuthorSales ASales ON A.author_id = ASales.author_id
WHERE ROWNUM = 1;

--For Mysql

WITH AuthorSales AS (
SELECT C.author_id, SUM(O.quantity) AS total_sales
FROM catalogue C
JOIN orderdetails O ON C.book_id = O.book_id
GROUP BY C.author_id
ORDER BY SUM(O.quantity) DESC
)
SELECT A.author_id, A.author_name
FROM author A
JOIN AuthorSales ASales ON A.author_id = ASales.author_id
LIMIT 1;

-- v) Demonstrate how to increase price of books published by specific publisher by


10%

UPDATE catalogue c
SET c.price = c.price + (c.price * 0.1)
WHERE c.publisher_id = 2002 ;

-- 2. Consider the following database for BANK.


-- BRANCH(branch-name: string, branch-city: string, assets: real)
-- ACCOUNT(accno: int, branch-name: string, balance: real)
-- DEPOSITOR(customer-name: string, accno: int)
-- CUSTOMER(customer-name: string, customer-street: string, customer-city: string)
-- LOAN(loan-no: int, branch-name: string, amount: real)
-- BORROWER(customer-name: string, loan-no: int)

-- i) Create the above tables by properly specifying the primary keys and foreign
keys.

CREATE TABLE branch(


branch_name VARCHAR(15) NOT NULL PRIMARY KEY,
branch_city VARCHAR(15),
assets INT(10)
);

CREATE TABLE account(


accno INT(8) NOT NULL PRIMARY KEY,
branch_name VARCHAR(15),
balance INT(10),
FOREIGN KEY(branch_name) REFERENCES branch(branch_name) ON DELETE CASCADE
);

CREATE TABLE customer(


customer_name VARCHAR(15) NOT NULL PRIMARY KEY,
customer_street VARCHAR(15),
customer_city VARCHAR(15)
);

CREATE TABLE loan(


loan_number INT(8) NOT NULL PRIMARY KEY,
branch_name VARCHAR(15),
amount INT(10),
FOREIGN KEY(branch_name) REFERENCES branch(branch_name) ON DELETE CASCADE
);

CREATE TABLE depositor(


customer_name VARCHAR(15),
accno INT(8),
PRIMARY KEY(customer_name, accno),
FOREIGN KEY(customer_name) REFERENCES customer(customer_name),
FOREIGN KEY(accno) REFERENCES account(accno)
);

CREATE TABLE borrower(


customer_name VARCHAR(15),
loan_number INT(8),
PRIMARY KEY(customer_name, loan_number),
FOREIGN KEY(customer_name) REFERENCES customer(customer_name),
FOREIGN KEY(loan_number) REFERENCES loan(loan_number)
);

-- ii) Enter atleast five tuples for each relation.

INSERT INTO branch


VALUES
('Main','c1',10000),
('b2','c2',20000),
('b3','c3',30000),
('b4','c4',40000),
('b5','c5',50000);

INSERT INTO account


VALUES
(12,'Main',3000),
(22,'b2',4000),
(32,'b3',5000),
(42,'b4',6000),
(52,'Main',7000),
(62,'b5',7000);

INSERT INTO customer


VALUES
('cust1','cstreet1','c1'),
('cust2','cstreet2','c2'),
('cust3','cstreet3','c3'),
('cust4','cstreet4','c4'),
('cust5','cstreet5','c5');

INSERT INTO depositor


VALUES
('cust1',12),
('cust2',22),
('cust3',32),
('cust4',42),
('cust1',52),
('cust5',62);

INSERT INTO loan


VALUES
(10,'Main',10000),
(20,'b2',20000),
(30,'b3',30000),
(40,'b4',40000),
(50,'b5',50000);

INSERT INTO borrower


VALUES
('cust1',10),
('cust2',20),
('cust3',30),
('cust4',40),
('cust5',50);

-- iii) Find all the customers who have atleast two accounts at the main branch.

SELECT DISTINCT D.customer_name


FROM DEPOSITOR D
INNER JOIN ACCOUNT A ON D.accno = A.accno
WHERE A.branch_name = 'Main'
GROUP BY D.customer_name
HAVING COUNT(DISTINCT A.accno) >= 2;

-- iv) Find all customer who have an account at all the branches located in a
specific city.

SELECT DISTINCT D.customer_name


FROM DEPOSITOR D
WHERE NOT EXISTS (
SELECT B.branch_name
FROM BRANCH B
WHERE B.branch_city = 'c2'
AND NOT EXISTS (
SELECT A.accno
FROM ACCOUNT A
WHERE A.branch_name = B.branch_name
AND A.accno = D.accno
)
);

-- 3. Consider the following database for ORDER PROCESSING.


-- CUSTOMER(cust-no: int, cname: string, city: string)
-- ORDER(orderno: int, odate: date, ord-amt: real)
-- ORDER_ITEM(orderno: int, itemno:int, qty: int)
-- ITEM(itemno: int, unitprice: real)
-- SHIPMENT(orderno: int, warehouseno: int, ship-date: date)
-- WAREHOUSE(warehouseno: int, city: string)

-- i) Create the above tables by properly specifying the primary keys and the
foreign keys

CREATE TABLE customer(


cust_no int(25),
cname char(25),
city char(25)
);

CREATE TABLE orders(


orderno int(25),
odate date,
ord_amt int(25)
);

CREATE TABLE order_item(


orderno int(25),
itemno int(25),
qty int(25)
);

CREATE TABLE item(


itemno int(25),
unitprice int(25)
);

CREATE TABLE shipment(


orderno int(25),
warehouseno int(25),
ship_date date
);

CREATE TABLE warehouse(


warehouseno int(25),
city char(25)
);

-- ii) Enter atleast five tuples for each relation.

INSERT INTO customer


VALUES
(100, 'Alex', 'Kolkata'),
(101, 'Mason', 'Delhi'),
(102, 'Ghost', 'Noida'),
(103, 'Antonio', 'Carol Bagh'),
(104, 'Sokolov', 'Noida');

INSERT INTO orders


VALUES
(990, '2023-06-09', 25000),
(991, '2023-01-12', 28000),
(992, '2023-05-05', 2000),
(993, '2023-06-23', 1200),
(994, '2023-03-10', 4050);

INSERT INTO order_item


VALUES
(990, 500, 5),
(991, 501, 15),
(992, 502, 10),
(993, 503, 2),
(994, 504, 3);

INSERT INTO item


VALUES
(500, 25),
(501, 50),
(502, 75),
(503, 100),
(504, 125);

INSERT INTO shipment


VALUES
(990, 5, '2023-06-27'),
(991, 10, '2023-05-27'),
(992, 15, '2023-04-19'),
(993, 20, '2023-01-30'),
(994, 25, '2023-07-08');

INSERT INTO warehouse


VALUES
(5, 'Kolkata'),
(10, 'Delhi'),
(15, 'Noida'),
(20, 'Carol Bagh'),
(25, 'Noida');

-- iii) List the order number and ship date for all orders shipped from particular
warehouse

SELECT O.orderno, S.ship_date


FROM ORDERS O
INNER JOIN SHIPMENT S ON O.orderno = S.orderno
INNER JOIN WAREHOUSE W ON S.warehouseno = W.warehouseno
WHERE W.city = 'Noida';

-- iv) Produce a listing: customer name, no of orders, average order amount

SELECT C.cname AS "Customer Name", COUNT(O.orderno) AS "No of Orders",


AVG(O.ord_amt) AS "Average Order Amount"
FROM CUSTOMER C
JOIN ORDERS O ON C.cust_no = O.cust_no
JOIN ORDER_ITEM OI ON O.orderno = OI.orderno
GROUP BY C.cname;

-- v) List the orders that were not shipped within 30 days of ordering

SELECT O.orderno, O.odate, S.ship_date


FROM ORDERS O
JOIN SHIPMENT S ON O.orderno = S.orderno
WHERE S.ship_date IS NULL OR (DATEDIFF(S.ship_date , O.odate)) > 30;

-- 1. Write a PL/SQL program to find the largest of three numbers

DECLARE
a NUMBER := 10;
b NUMBER := 20;
c NUMBER := 15;
largest NUMBER;
BEGIN
IF (a >= b) AND (a >= c) THEN
largest := a;
ELSIF (b >= a) AND (b >= c) THEN
largest := b;
ELSE
largest := c;
END IF;

DBMS_OUTPUT.PUT_LINE('The largest number among ' || a || ', ' || b || ', and '
|| c || ' is ' || largest);
END;

-- 2. Write a PL/SQL program to generate reverse for given number

DECLARE
n NUMBER(4) := 5;
s NUMBER(4) := 8;
r NUMBER(4);
BEGIN
WHILE n > 0 LOOP
r := MOD(n, 10);
s := (s * 10) + r;
n := TRUNC(n / 10);
END LOOP;

DBMS_OUTPUT.put_line('The reverse number is: ' || s);


END;

-- 3. Write a PL/SQL program to find the factorial of a given number

DECLARE
n NUMBER(4) := 5;
f NUMBER(4) := 1;
result NUMBER(4);
BEGIN
FOR i IN 1..n LOOP
f := f * i;
END LOOP;

result := f;

DBMS_OUTPUT.put_line('The factorial of ' || n || ' is: ' || result);


END;

-- 4. Write a PL/SQL program to check whether given number is prime or no

DECLARE
n NUMBER(4) := 3;
is_prime BOOLEAN := TRUE;

BEGIN
IF n <= 1 THEN
is_prime := FALSE;
ELSE
FOR i IN 2..TRUNC(SQRT(n)) LOOP
IF MOD(n, i) = 0 THEN
is_prime := FALSE;
EXIT;
END IF;
END LOOP;
END IF;

IF is_prime THEN
DBMS_OUTPUT.put_line(n || ' is a prime number.');
ELSE
DBMS_OUTPUT.put_line(n || ' is not a prime number.');
END IF;
END;

-- 5. Write a PL/SQL program to generate Fibonacci series upto N

DECLARE
n NUMBER(4) := 10;
a NUMBER(4) := 0;
b NUMBER(4) := 1;
fib NUMBER(4);

BEGIN
DBMS_OUTPUT.put_line('Fibonacci series up to ' || n || ':');

IF n >= 1 THEN
DBMS_OUTPUT.put_line(a);
END IF;

IF n >= 2 THEN
DBMS_OUTPUT.put_line(b);
END IF;

FOR i IN 3..n LOOP


fib := a + b;
DBMS_OUTPUT.put_line(fib);
a := b;
b := fib;
END LOOP;
END;

-- 6. Write a PL/SQL program for calculating sum of two numbers. [NOT WORKING]

DECLARE
num1 NUMBER := 10;
num2 NUMBER := 20;
sum_result NUMBER;
BEGIN
sum_result := num1 + num2;
DBMS_OUTPUT.PUT_LINE('The sum of ' || num1 || ' and ' || num2 || ' is: ' ||
sum_result);
END;

-- 7. Write a PL/SQL program to check the given year is leap year or not

DECLARE
year_to_check NUMBER := 2016;
is_leap BOOLEAN := FALSE;
BEGIN
-- Check if the year is divisible by 4
IF (MOD(year_to_check, 4) = 0) THEN
IF (MOD(year_to_check, 100) <> 0 OR MOD(year_to_check, 400) = 0) THEN
is_leap := TRUE;
END IF;
END IF;

IF is_leap THEN
DBMS_OUTPUT.PUT_LINE(year_to_check || ' is a leap year.');
ELSE
DBMS_OUTPUT.PUT_LINE(year_to_check || ' is not a leap year.');
END IF;
END;

-- 8. Find the sum of the digits of a given number

DECLARE
number_to_sum NUMBER := 566;
digit_sum NUMBER := 0;
temp_number NUMBER;
BEGIN
temp_number := number_to_sum;

-- Loop to calculate the sum of digits


WHILE temp_number > 0 LOOP
digit_sum := digit_sum + MOD(temp_number, 10);
temp_number := TRUNC(temp_number / 10);
END LOOP;

DBMS_OUTPUT.PUT_LINE('The sum of the digits of ' || number_to_sum || ' is ' ||


digit_sum);
END;

-- 9. Check the number of vowels and consonants in a given string


DECLARE
input_string VARCHAR2(100) := 'Hello, World!';
num_vowels NUMBER := 0;
num_consonants NUMBER := 0;
i NUMBER;
character VARCHAR2(1);
BEGIN
input_string := UPPER(input_string);

FOR i IN 1..LENGTH(input_string) LOOP


character := SUBSTR(input_string, i, 1);

IF REGEXP_LIKE(character, '[A-Z]') THEN


IF character IN ('A', 'E', 'I', 'O', 'U') THEN
num_vowels := num_vowels + 1;
ELSE
num_consonants := num_consonants + 1;
END IF;
END IF;
END LOOP;

DBMS_OUTPUT.PUT_LINE('Input String: ' || input_string);


DBMS_OUTPUT.PUT_LINE('Number of Vowels: ' || num_vowels);
DBMS_OUTPUT.PUT_LINE('Number of Consonants: ' || num_consonants);
END;

-- 10. Count odd and even digits in a number

DECLARE
input_number NUMBER := 123456789; --
num_even NUMBER := 0;
num_odd NUMBER := 0;
temp_number NUMBER;
digit NUMBER;
BEGIN
temp_number := input_number;

WHILE temp_number > 0 LOOP


digit := MOD(temp_number, 10);
IF MOD(digit, 2) = 0 THEN
num_even := num_even + 1;
ELSE
num_odd := num_odd + 1;
END IF;
temp_number := TRUNC(temp_number / 10);
END LOOP;

DBMS_OUTPUT.PUT_LINE('Input Number: ' || input_number);


DBMS_OUTPUT.PUT_LINE('Number of Even Digits: ' || num_even);
DBMS_OUTPUT.PUT_LINE('Number of Odd Digits: ' || num_odd);
END;

You might also like