0% found this document useful (0 votes)
20 views40 pages

DBMS Experiments

Contains various experiments on database management system subject with various examples

Uploaded by

prithvi.ch.79
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)
20 views40 pages

DBMS Experiments

Contains various experiments on database management system subject with various examples

Uploaded by

prithvi.ch.79
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/ 40

Experiment 1:

Aim: Explain the languages.

In database management systems, there are five main types of languages:

1. Data Definition Language (DDL):


○ Used to define the structure of the database. Commands:
■ CREATE: Used to create a new table or database.
■ ALTER: Modify an existing database object, such as a table.
■ DROP: Delete a table or database.
■ TRUNCATE: Remove all records from a table, but keep its structure.

2. Data Manipulation Language (DML):


○ Used to manipulate data within tables.
○ Commands:
■ SELECT: Retrieve data from a table.
■ INSERT: Add new data to a table.
■ UPDATE: Modify existing data in a table.
■ DELETE: Remove data from a table.

3. Data Control Language (DCL):


○ Used to control access to data in the database. Commands:
■ GRANT: Give user access privileges to the database.
■ REVOKE: Remove user access privileges.

4. Transaction Control Language (TCL):


○ Used to manage transactions in the database. Commands:
■ COMMIT: Save changes made in the database.
■ ROLLBACK: Undo changes made in the current transaction.
■ SAVEPOINT: Set a point to which a transaction can be rolled back.

5. Query Language (QL):


○ Primarily used to query data from the database using SELECT statements.
○ SQL is the most commonly used query language.

Prithvi Singh Chauhan A2305222248


Experiment 2

Aim: Functions in SQL.

SQL functions are used to perform calculations on data. Here are some categories of
functions and their uses:

1. Aggregate Functions:

These functions operate on a collection of values to return a single value.

● COUNT(): Returns the number of rows that match a specified condition.

SELECT COUNT(*) AS TotalEmployees FROM employees;

This will return the total number of employees in the employees table.

● SUM(): Returns the sum of a numeric column.

SELECT SUM(salary) AS TotalSalary

FROM employees WHERE department = 'HR'

This will return the total salary of all employees in the HR department.

● AVG(): Returns the average value of a numeric column.

SELECT AVG(salary) AS AverageSalary FROM employees;

This will return the average salary of all employees.

● MAX(): Returns the maximum value in a column.

SELECT MAX(salary) AS HighestSalary FROM employees;

This will return the highest salary among the employees.

● MIN(): Returns the minimum value in a column.

SELECT MIN(salary) AS LowestSalary FROM employees;

This will return the lowest salary among the employees.

Prithvi Singh Chauhan A2305222248


2. String Functions:

String functions allow you to manipulate and perform operations on strings.

● CONCAT(): Concatenates two or more strings into one.

SELECT CONCAT(first_name, ' ', last_name) AS FullName FROM


employees;

This will return the full name of each employee by combining their first and last
names.

● SUBSTRING(): Extracts a substring from a string.

SELECT SUBSTRING(employee_code, 1, 3) AS CodePrefix FROM


employees;

This will extract the first three characters of the employee_code for each employee.

● LENGTH(): Returns the length of a string.

SELECT LENGTH(first_name) AS NameLength FROM employees;

This will return the length of each employee's first name.

● UPPER(): Converts a string to uppercase.

SELECT UPPER(last_name) AS UpperLastName FROM employees;

This will return the last name of each employee in uppercase.

● LOWER(): Converts a string to lowercase.

SELECT LOWER(first_name) AS LowerFirstName FROM employees;

This will return the first name of each employee in lowercase.

Prithvi Singh Chauhan A2305222248


3. Date Functions:

These functions allow you to manipulate and retrieve information from date values.

● NOW(): Returns the current date and time.

SELECT NOW() AS CurrentDateTime;

This will return the current system date and time.

● CURDATE(): Returns the current date.

SELECT CURDATE() AS CurrentDate;

This will return the current system date.

● DATEADD(): Adds a specified time interval to a date.

SELECT DATEADD(NOW(), INTERVAL 7 DAY) AS NextWeek;

This will return the date exactly 7 days from the current date.

● DATEDIFF(): Returns the difference between two dates.

SELECT DATEDIFF(NOW(), hire_date) AS DaysEmployed FROM


employees;

This will return the number of days each employee has been employed by calculating
the difference between the current date and their hire_date.

Prithvi Singh Chauhan A2305222248


4. Mathematical Functions:

These functions are used to perform arithmetic calculations.

● ROUND(): Rounds a number to the nearest integer or specified number of decimal


places.

SELECT ROUND(salary, 2) AS RoundedSalary FROM employees;

This will return the salary of each employee rounded to two decimal places.

● ABS(): Returns the absolute (positive) value of a number.

SELECT ABS(salary_change) AS AbsoluteSalaryChange FROM


salary_changes;

This will return the absolute value of the salary change, ensuring there are no negative
values.

● MOD(): Returns the remainder of a division operation.

SELECT MOD(15, 4) AS Remainder;

This will return the remainder when 15 is divided by 4 (which is 3).

Prithvi Singh Chauhan A2305222248


Experiment 3

Aim: Keys: Foreign and Primary

Primary Key

● Definition: A primary key is a unique identifier for a record in a database table.


● Uniqueness: Each value in the primary key column must be unique, ensuring no two
rows have the same key value.
● Non-null: Primary keys cannot contain null values, meaning every record must have a
valid key.
● Single Column: It can be a single column or a combination of columns (composite
key).
● Purpose: Used to enforce entity integrity by uniquely identifying each record in a
table.

Example:

CREATE TABLE Employees (


EmployeeID INT NOT NULL,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Email VARCHAR(100),
PRIMARY KEY (EmployeeID)
);

The SQL query creates an Employees table to store employee information. It defines four
columns: EmployeeID, FirstName, LastName, and Email, with appropriate data types. The
EmployeeID column is designated as the primary key, ensuring each identifier is unique and
cannot be null. This setup enforces data integrity by guaranteeing that every employee has a
distinct identifier, which is essential for managing and referencing records accurately in the
database.

Prithvi Singh Chauhan A2305222248


Foreign Key

● Definition: A foreign key is a field (or a collection of fields) in one table that
uniquely identifies a row in another table.
● Relationship: Establishes a link between the data in two tables, creating a
relationship.
● Referential Integrity: Foreign keys allow for referential integrity by ensuring that the
value in the foreign key column must match a primary key value in the referenced
table or be null.
● Multiple Values: A foreign key can have duplicate values in the referencing table,
allowing for many-to-one relationships.
● Purpose: Used to create relationships between tables, facilitating data normalization
and reducing redundancy.

Example:

CREATE TABLE Departments (


DepartmentID INT NOT NULL,
DepartmentName VARCHAR(50),
PRIMARY KEY (DepartmentID)
);

CREATE TABLE Employees (


EmployeeID INT NOT NULL,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Email VARCHAR(100),
DepartmentID INT,
PRIMARY KEY (EmployeeID),
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
);

In this example, two tables are created: Departments and Employees. The Departments table
has a primary key, DepartmentID, to uniquely identify each department. In the Employees
table, the DepartmentID column serves as a foreign key, establishing a link between
employees and their respective departments. This foreign key constraint ensures that any
value entered in the DepartmentID column of the Employees table must correspond to a valid
DepartmentID in the Departments table, thus enforcing referential integrity and ensuring
meaningful relationships between the two tables.

Prithvi Singh Chauhan A2305222248


Experiment 4,5,6 All the Required Tables

Prithvi Singh Chauhan A2305222248


Prithvi Singh Chauhan A2305222248
Experiment 4

Aim: Client Product Subqueries

● Find products sold to 'Ivan Bayross':

SELECT SOD.ProductNo, PM.Description


FROM Sales_Order_Details SOD, Sales_Order SO, Product_Master
PM, Client_Master CM
WHERE PM.ProductNo = SOD.ProductNo
AND CM.ClientNo = SO.ClientNo
AND CM.Name = 'Ivan Bayross';

● Products and quantities to be delivered in the current month:

SELECT SOD.ProductNo, PM.Description, SUM(SOD.QtyDisp)


FROM Sales_Order SO, Sales_Order_Details SOD, Product_Master
PM
WHERE SO.OrderNo = SOD.OrderNo
AND SO.OrderStatus = 'Fulfilled'
AND SO.DelyDate BETWEEN TO_DATE('01-'||TO_CHAR(SYSDATE,
'MON-YYYY'), 'DD-MON-YYYY')
AND LAST_DAY(SYSDATE)
GROUP BY SOD.ProductNo, PM.Description;

Prithvi Singh Chauhan A2305222248


● Finding the clients who have placed orders before the month of May'02.

SELECT ClientNo, Name FROM Client_Master


WHERE ClientNo IN(
SELECT ClientNo FROM
Sales_Order
WHERE OrderDate >= '2002-05-01' AND OrderDate < '2002-06-01'
);

● Finding the non-moving products i.e. products not being sold.

SELECT ProductNo, Description


FROM Product_Master
WHERE ProductNo NOT IN (
SELECT ProductNo
FROM Sales_Order_Details
);

Prithvi Singh Chauhan A2305222248


Experiment 5

Aim: Client product group by.

● Total quantity sold for each product:

SELECT description, SUM(QtyDisp)


FROM Product_Master, Sales_Order_Details
WHERE Product_Master.ProductNo = Sales_Order_Details.ProductNo
GROUP BY Description;

● Value of each product sold:

SELECT Sales_Order_Details.ProductNo, Product_Master.Description,


SUM(Sales_Order_Details.QtyDisp * Sales_Order_Details.ProductRate)
'Sales Per Product'
FROM Sales_Order_Details, Product_Master
WHERE Product_Master.ProductNo = Sales_Order_Details.ProductNo
GROUP BY Sales_Order_Details.ProductNo, Product_Master.Description;

Prithvi Singh Chauhan A2305222248


● Average quantity sold for clients with max order value > 15000:

SELECT CM.ClientNo, CM.Name, AVG(SOD.QtyDisp) 'Avg. Sales'


FROM Sales_Order_Details SOD, Sales_Order SO, Client_Master CM
WHERE CM.ClientNo = SO.ClientNo AND SO.OrderNo = SOD.OrderNo
GROUP BY CM.ClientNo, Name
HAVING MAX(SOD.QtyOrdered * SOD.ProductRate) > 15000;

Prithvi Singh Chauhan A2305222248


● Total billed orders for June:

SELECT SO.OrderNo, SO.OrderDate, SUM(SOD.QtyOrdered *


SOD.ProductRate) 'Order Billed'

FROM Sales_Order SO, Sales_Order_Details SOD

WHERE SOD.OrderNo = SO.OrderNo AND SO.Billed = 'Y'

AND to_char(OrderDate, 'MON') = 'Jun'

GROUP BY SO.OrderNo;

Prithvi Singh Chauhan A2305222248


Experiment 6

Aim: Client Product join

● Join CLIENT_MASTER and PRODUCT_MASTER on sales data:

SELECT CM.ClientNo, CM.Name, PM.ProductNo, PM.Description,


SUM(SOD.QtyOrdered) AS TotalOrdered
FROM Client_Master CM
JOIN Sales_Order SO ON CM.ClientNo = SO.ClientNo
JOIN Sales_Order_Details SOD ON SO.OrderNo = SOD.OrderNo
JOIN Product_Master PM ON SOD.ProductNo = PM.ProductNo
GROUP BY CM.ClientNo, CM.Name, PM.ProductNo, PM.Description;

Prithvi Singh Chauhan A2305222248


● Find clients and the total quantity of products they purchased:

SELECT CM.ClientNo, CM.Name, SUM(SOD.QtyOrdered) AS


TotalQuantityPurchased
FROM Client_Master CM
JOIN Sales_Order SO ON CM.ClientNo = SO.ClientNo
JOIN Sales_Order_Details SOD ON SO.OrderNo = SOD.OrderNo
GROUP BY CM.ClientNo, CM.Name;

● Join to display salesmen, clients, and their respective orders:

SELECT SM.SalesmanNo, SM.SalesmanName, CM.ClientNo, CM.Name,


SO.OrderNo
FROM Salesman_Master SM
JOIN Sales_Order SO ON SM.SalesmanNo = SO.SalesmanNo
JOIN Client_Master CM ON SO.ClientNo = CM.ClientNo;

Prithvi Singh Chauhan A2305222248


Experiment 7

Aim: Given a relational database, create expressions in QBE for each of the
SQL queries.

In QBE (Query by Example), the queries are written in a graphical format where you fill in
values into templates to describe what data you want to manipulate or retrieve.

Relational Schema

● Employee(personname, street, city)


● Works(personname, companyname, salary)
● Company(companyname, city)
● Manages(personname, managername)

1. Creating the Tables:

-- Create Employee table


CREATE TABLE Employee (
personname VARCHAR(50) PRIMARY KEY,
street VARCHAR(100),
city VARCHAR(50)
);

-- Create Works table


CREATE TABLE Works (
personname VARCHAR(50),
companyname VARCHAR(50),
salary DECIMAL(10, 2),
PRIMARY KEY (personname, companyname),
FOREIGN KEY (personname) REFERENCES Employee(personname)
);

-- Create Company table


CREATE TABLE Company (
companyname VARCHAR(50) PRIMARY KEY,
city VARCHAR(50)
);

-- Create Manages table


CREATE TABLE Manages (
personname VARCHAR(50),

Prithvi Singh Chauhan A2305222248


managername VARCHAR(50),
PRIMARY KEY (personname, managername),
FOREIGN KEY (personname) REFERENCES Employee(personname),
FOREIGN KEY (managername) REFERENCES Employee(personname)
);

Prithvi Singh Chauhan A2305222248


2. Inserting sample data:

-- Insert into Employee table


INSERT INTO Employee VALUES
('Jones', '123 Elm St', 'Oldtown'),
('Smith', '456 Oak St', 'Oldtown'),
('Allen', '789 Pine St', 'Newtown'),
('Miller', '234 Maple St', 'Oldtown'),
('Davis', '567 Birch St', 'Newtown');

-- Insert into Company table


INSERT INTO Company VALUES
('First Bank Corporation', 'Oldtown'),
('Small Bank Corporation', 'Newtown'),
('Global Tech', 'Oldtown');

-- Insert into Works table


INSERT INTO Works VALUES
('Jones', 'First Bank Corporation', 80000),
('Smith', 'Small Bank Corporation', 50000),
('Allen', 'First Bank Corporation', 120000),
('Miller', 'Global Tech', 90000),
('Davis', 'Small Bank Corporation', 45000);

-- Insert into Manages table


INSERT INTO Manages VALUES
('Jones', 'Miller'),
('Smith', 'Jones'),
('Allen', 'Jones');

Prithvi Singh Chauhan A2305222248


Prithvi Singh Chauhan A2305222248
3. QBE expressions:

1. Modify the database so that Jones now lives in Newtown:

UPDATE Employee
SET city = 'Newtown'
WHERE personname = 'Jones';

2. Give all employees of First Bank Corporation a 10% raise:

UPDATE Works
SET salary = salary * 1.10
WHERE companyname = 'First Bank Corporation';

3. Give all managers in the database a 10% raise:

UPDATE Works
SET salary = salary * 1.10
WHERE personname IN (SELECT personname FROM Manages);

4. Give all managers a 10% raise unless the salary would be greater than
Rs.100,000. In such a case, give only a 3% raise:

UPDATE Works
SET salary = CASE
WHEN salary * 1.10 > 100000 THEN salary * 1.03
ELSE salary * 1.10
, END
WHERE personname IN (SELECT personname FROM Manages);

Prithvi Singh Chauhan A2305222248


Experiment 8

Aim: Construct the SQL queries for the given relational database

Consider the following relation:

patients (pnum, pname, age)


doctors (dnum, dname, rank)
visits (pnum, dnum, date, diagnosis)

Construct the SQL queries for the following


● Who are the patients 10 years old or younger?
● Who are the surgeons
● What are the phone numbers of doctors
● What are the phone numbers of surgeons

1. Creating Tables:

-- Create the patients table


CREATE TABLE patients (
pnum INT PRIMARY KEY,
pname VARCHAR(50),
age INT
);

-- Create the doctors table


CREATE TABLE doctors (
dnum INT PRIMARY KEY,
dname VARCHAR(50),
rank VARCHAR(50),
phone_number VARCHAR(15) -- Assuming phone numbers are part of
this table
);

CREATE TABLE visits (


pnum INT,
dnum INT,
visit_date DATE,
diagnosis VARCHAR(100),
PRIMARY KEY (pnum, dnum, visit_date),
FOREIGN KEY (pnum) REFERENCES patients(pnum),
FOREIGN KEY (dnum) REFERENCES doctors(dnum)
);

Prithvi Singh Chauhan A2305222248


2. Insert Sample Data:

INSERT INTO patients VALUES


(1, 'John Doe', 8),
(2, 'Jane Smith', 12),
(3, 'Emily White', 6),
(4, 'Michael Brown', 14),
(5, 'Alex Green', 10);

Prithvi Singh Chauhan A2305222248


INSERT INTO doctors VALUES
(101, 'Dr. James', 'surgeon', '123-456-7890'),
(102, 'Dr. Sarah', 'physician', '123-456-7891'),
(103, 'Dr. Mike', 'surgeon', '123-456-7892'),
(104, 'Dr. Emily', 'consultant', '123-456-7893');

INSERT INTO visits VALUES


(1, 101, '2023-01-10', 'Flu'),
(2, 102, '2023-02-15', 'Cold'),
(3, 103, '2023-03-18', 'Fever'),
(4, 104, '2023-04-22', 'Headache'),
(5, 101, '2023-05-10', 'Surgery');

Prithvi Singh Chauhan A2305222248


3. SQL Queries

i. Who are the patients 10 years old or younger?

SELECT pname
FROM patients
WHERE age <= 10;

This query selects the names of all patients who are 10 years old or younger.

ii. Who are the surgeons?

SELECT dname
FROM doctors
WHERE rank = 'surgeon';

This query selects the names of all doctors who are surgeons.

Prithvi Singh Chauhan A2305222248


iii. What are the phone numbers of doctors?

SELECT dname, phone_number


FROM doctors;

This query selects the names and phone numbers of all doctors.

iv. What are the phone numbers of surgeons?

SELECT dname, phone_number


FROM doctors
WHERE rank = 'surgeon';

This query selects the names and phone numbers of doctors who are surgeons.

Prithvi Singh Chauhan A2305222248


Experiment 9

Aim: Assignment 4.

1. Create the EMP and DEPT tables:

CREATE TABLE EMP (


EMPNO NUMBER,
ENAME VARCHAR2(50),
JOB CHAR(20),
MGR NUMBER,
HIREDATE DATE,
SAL NUMBER,
COMM NUMBER,
DEPTNO NUMBER
);

CREATE TABLE DEPT (


DEPTNO NUMBER,
DNAME VARCHAR2(50),
LOC VARCHAR2(50)
);

2. Insert the provided data:

Inserting into DEPT table:

INSERT INTO DEPT VALUES (10, 'Accounting', 'New York');


INSERT INTO DEPT VALUES (20, 'Research', 'Dallas');
INSERT INTO DEPT VALUES (30, 'Sales', 'Chicago');
INSERT INTO DEPT VALUES (40, 'Operations', NULL);

Prithvi Singh Chauhan A2305222248


Inserting into EMP table:

INSERT INTO EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM,
DEPTNO) VALUES
(7369, 'Smith', 'Clerk', 7902, '1980-12-17', 800, NULL, 20),
(7499, 'Allen', 'Salesman', 7698, '1981-02-20', 1600, 300, 30),
(7521, 'Ward', 'Salesman', 7698, '1981-02-22', 1250, 500, 30),
(7566, 'Jones', 'Manager', 7839, '1981-04-02', 2975, NULL, 20),
(7654, 'Martin', 'Salesman', 7698, '1981-09-28', 1250, 1400, 30),
(7698, 'Blake', 'Manager', 7839, '1981-05-01', 2850, NULL, 30),
(7782, 'Clark', 'Manager', 7839, '1981-06-09', 2450, NULL, 10),
(7788, 'Scott', 'Analyst', 7566, '1982-12-09', 3000, NULL, 20),
(7839, 'King', 'President', NULL, '1981-11-17', 5000, NULL, 10),
(7844, 'Turner', 'Salesman', 7698, '1981-09-08', 1500, 0, 30),
(7876, 'Adams', 'Clerk', 7788, '1983-01-12', 1100, NULL, 20),
(7900, 'James', 'Clerk', 7698, '1981-12-03', 950, NULL, 30),
(7902, 'Ford', 'Analyst', 7566, '1981-12-04', 3000, NULL, 20),
(7934, 'Miller', 'Clerk', 7782, '1982-01-23', 1300, NULL, 10);

Prithvi Singh Chauhan A2305222248


1. List the names of analysts and salesmen.

SELECT ENAME FROM EMP WHERE JOB IN ('Analyst', 'Salesman');

2. List details of employees who have joined before 30 Sep 81.

SELECT * FROM EMP WHERE HIREDATE < '1981-09-30';

3. List names of employees who are not managers.

SELECT ENAME FROM EMP WHERE JOB <> 'Manager';

Prithvi Singh Chauhan A2305222248


4. List the names of employees whose employee numbers are 7369, 7521, 7839,
7934, 7788.

SELECT ENAME FROM EMP WHERE EMPNO IN (7369, 7521, 7839, 7934,
7788);

5. List employees not belonging to department 30, 40, or 10.

SELECT ENAME FROM EMP WHERE DEPTNO NOT IN (30, 40, 10);

6. List employee names for those who have joined between 30 June and 31 Dec. ‘81.

SELECT ENAME FROM EMP WHERE HIREDATE BETWEEN '1981-06-30' AND


'1981-12-31';

Prithvi Singh Chauhan A2305222248


7. List the different designations in the company.

SELECT DISTINCT JOB FROM EMP;

8. List the names of employees who are not eligible for commission.

SELECT ENAME FROM EMP WHERE COMM IS NULL OR COMM = 0;

9. List the name and designation of the employee who does not report to anybody.

SELECT ENAME, JOB FROM EMP WHERE MGR IS NULL;

10. List the employees not assigned to any department.

SELECT ENAME FROM EMP WHERE DEPTNO IS NULL;

Prithvi Singh Chauhan A2305222248


11. List the employees who are eligible for commission.

SELECT ENAME FROM EMP WHERE COMM IS NOT NULL AND COMM > 0;

12. List employees whose names either start or end with “S”.

SELECT ENAME FROM EMP WHERE ENAME LIKE 'S%' OR ENAME LIKE
'%S';

13. List names of employees whose names have “i” as the second character.

SELECT ENAME FROM EMP WHERE ENAME LIKE '_i%';

14. List the number of employees working with the company.

SELECT COUNT(*) FROM EMP;

Prithvi Singh Chauhan A2305222248


15. List the number of designations available in the EMP table.

SELECT COUNT(DISTINCT JOB) FROM EMP;

16. List the total salaries paid to the employees.

SELECT SUM(SAL) FROM EMP;

17. List the maximum, minimum, and average salary in the company.

SELECT MAX(SAL) AS MaxSalary, MIN(SAL) AS MinSalary, AVG(SAL)


AS AvgSalary FROM EMP;

18. List the maximum salary paid to a salesman.

SELECT MAX(SAL) AS MaxSalary FROM EMP WHERE JOB = 'Salesman';

Prithvi Singh Chauhan A2305222248


Experiment 10

Aim: Company assignment.

1. Create required tables:

- Create the EMPLOYEE table-


CREATE TABLE employee (
employeename VARCHAR(20) PRIMARY KEY,
street VARCHAR(20),
city VARCHAR(20)
);

-- Create the COMPANY table


CREATE TABLE company (
companyname VARCHAR(20) PRIMARY KEY,
city VARCHAR(20)
);

-- Create the WORKS table


CREATE TABLE works (
employeename VARCHAR(20),
companyname VARCHAR(20),
salary DOUBLE,
PRIMARY KEY (employeename, companyname),
FOREIGN KEY (employeename) REFERENCES employee(employeename),
FOREIGN KEY (companyname) REFERENCES company(companyname)
);

-- Create the MANAGES table


CREATE TABLE manages (
employeename VARCHAR(20),
managername VARCHAR(20),
PRIMARY KEY (employeename, managername),
FOREIGN KEY (employeename) REFERENCES employee(employeename),
FOREIGN KEY (managername) REFERENCES employee(employeename)
);

Prithvi Singh Chauhan A2305222248


2. Insert Data into Tables:

-- Insert data into the EMPLOYEE table


INSERT INTO employee (employeename, street, city) VALUES
('Neha', 'A street', 'A city'),
('Reesha', 'B street', 'B city'),
('Ritika', 'C street', 'C city'),
('Ritu', 'C street', 'C city'),
('Ryan', 'A street', 'A city');

-- Insert data into the COMPANY table


INSERT INTO company (companyname, city) VALUES
('First Bank Corporation', 'A city'),
('Small Bank Corporation', 'B city'),
('No Bank Corporation', 'C city'),
('Yes Bank Corporation', 'A city'),
('More Bank Corporation', 'B city');

Prithvi Singh Chauhan A2305222248


-- Insert data into the WORKS table
INSERT INTO works (employeename, companyname, salary) VALUES
('Neha', 'First Bank Corporation', 40000),
('Reesha', 'Small Bank Corporation', 30000),
('Ritika', 'No Bank Corporation', 35000),
('Ritu', 'Small Bank Corporation', 25000),
('Ryan', 'First Bank Corporation', 15000);

-- Insert data into the MANAGES table


INSERT INTO manages (employeename, managername) VALUES
('Neha', 'Ryan'),
('Neha', 'Kelly'),
('Reesha', 'Ritu');

Prithvi Singh Chauhan A2305222248


3. Queries:

1. Find names, street address, and cities of residence for employees who work for
'First Bank Corporation' and earn more than $10,000.

SELECT e.employeename, e.street, e.city


FROM employee e
JOIN works w ON e.employeename = w.employeename
WHERE w.companyname = 'First Bank Corporation' AND w.salary >
10000;

2. Find names of all employees who live in the same cities as the companies for
which they work.

SELECT e.employeename
FROM employee e
JOIN works w ON e.employeename = w.employeename
JOIN company c ON w.companyname = c.companyname
WHERE e.city = c.city;

3. Find the average salary company-wise.

SELECT w.companyname, AVG(w.salary) AS "Average Salary"


FROM works w
GROUP BY w.companyname;

Prithvi Singh Chauhan A2305222248


4. Find names of employees who live in the same cities and on the same streets as
their managers.

SELECT e.employeename
FROM employee e
JOIN manages m ON e.employeename = m.employeename
JOIN employee mgr ON m.managername = mgr.employeename
WHERE e.city = mgr.city AND e.street = mgr.street;

5. Find names of employees who do not work for 'First Bank Corporation'.

SELECT DISTINCT e.employeename


FROM employee e
WHERE e.employeename NOT IN (SELECT employeename FROM works
WHERE companyname = 'First Bank Corporation');

6. Find names of employees who earn more than every employee of 'Small Bank
Corporation'.

SELECT employeename
FROM works
WHERE salary > (SELECT MAX(salary) FROM works WHERE companyname =
'Small Bank Corporation');

Prithvi Singh Chauhan A2305222248


7. Find names, street address, and cities of residence for employees who work for
'First Bank Corporation' and earn between $10,000 and $20,000.

SELECT e.employeename, e.street, e.city


FROM employee e
JOIN works w ON e.employeename = w.employeename
WHERE w.companyname = 'First Bank Corporation' AND w.salary
BETWEEN 10000 AND 20000;

8. Find names of employees who live in the same cities as the companies for which
they work.

SELECT e.employeename
FROM employee e
JOIN works w ON e.employeename = w.employeename
JOIN company c ON w.companyname = c.companyname
WHERE e.city = c.city;

Prithvi Singh Chauhan A2305222248


9. Find names of employees who earn more than every employee of 'Small Bank
Corporation'.

SELECT employeename
FROM works
WHERE salary > (SELECT MAX(salary) FROM works WHERE
companyname = 'Small Bank Corporation');

Prithvi Singh Chauhan A2305222248

You might also like