0% found this document useful (0 votes)
32 views47 pages

Dbms Lab Report - 230709

Uploaded by

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

Dbms Lab Report - 230709

Uploaded by

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

SCHOOL OF ENGINEERING &

TECHNOLOGY
B.TECH. COMPUTER SCIENCE &
ENGINEERING

Database Management System


LABORATORY FILE
AUG - DEC 2024

SUBMITTED BY

YASH YADAV
230709
B.Tech CSE
INDEX

S. Faculty
Name of Experiment Date
No. Sign
22.08.20
01. SCHEMA
24
08.10.20
02. JOINS
24
17.10.20
03. SUB-QUERIES
24
11.11.20
04. VIEWS
24
11.11.20
05. FUNCTIONS
24
14.11.20
06. STORED PROCEDURES
24
Q1 - Suppose you are given the following requirements for a simple database for the National
Hockey League (NHL):
The NHL has many teams, each team has a name, a city, a coach, a captain, and a set of
players.
Each player belongs to only one team. Each player has a name, a position (such as left wing
or goalie), a skill level, and a set of injury records, · a team captain is also a player. A game is
played between two teams (referred to as host_team and guest_team) and has a date (such as
May 11th, 1999) and a score (such as 4 to 2).

CREATE TABLE YASH_TEAM (


team_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
city VARCHAR(100) NOT NULL,
coach VARCHAR(100) NOT NULL,
captain_id INT,
);
INSERT INTO YASH_TEAM(team_id,name, city, coach, captain_id)
VALUES (101,'Maple Leafs', 'Toronto', 'Sheldon Keefe', 1);
INSERT INTO YASH_TEAM(team_id,name, city, coach, captain_id)
VALUES (102,'Canadiens', 'Montreal', 'Martin St. Louis', 2);
INSERT INTO YASH_TEAM(team_id,name, city, coach, captain_id)
VALUES (103,'Bruins', 'Boston', 'Jim Montgomery', 3);
SELECT * FROM YASH_TEAM;

CREATE TABLE YASH_PLAYERS (


player_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
position VARCHAR(50) NOT NULL,
skill_level INT NOT NULL,
team_id INT,
FOREIGN KEY (team_id) REFERENCES YASH_TEAM(team_id)
);

INSERT INTO YASH_PLAYERS (player_id,name, position, skill_level, team_id)


VALUES (1,'John Tavares', 'Center', 90, 101);

INSERT INTO YASH_PLAYERS(player_id,name, position, skill_level, team_id)


VALUES (2,'Auston Matthews', 'Center', 95, 101);

INSERT INTO YASH_PLAYERS(player_id,name, position, skill_level, team_id)


VALUES (3,'Carey Price', 'Goalie', 92, 102);

SELECT * FROM YASH_PLAYERS;

CREATE TABLE YASH_GAMES (


game_id INT PRIMARY KEY,
host_team_id INT,
guest_team_id INT,
game_date DATE NOT NULL,
host_team_score INT NOT NULL,
guest_team_score INT NOT NULL,
);
SELECT * FROM YASH_GAMES;
Q2 - Suppose that you are designing a schema to record information about reality shows on
TV. Your database needs to record the following information: For each reality show, its
name, genre, basic_info and participants name. Any reality show has at least two or more
participants. For each producer, the company name, company country. A show is produced
by exactly one producer. And one producer produces exactly one show. For each television,
its name, start year, head office. A television may broadcasts multiple shows. Each show is
broadcasted by exactly one television. For each user, his/her username, password, and age. A
user may rate multiple shows, and a show may be rated by multiple users. Each rating has a
score of 0 to 10.Construct the SQL tables based on Relational model defined earlier.

CREATE TABLE YASH_RealityShows (


show_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
genre VARCHAR(50),
basic_info TEXT,
producer_id INT,
television_id INT,
FOREIGN KEY (producer_id) REFERENCES YASH_Producers (producer_id),
FOREIGN KEY (television_id) REFERENCES YASH_Televisions(television_id)
);

CREATE TABLE YASH_Producers (


producer_id INT PRIMARY KEY,
company_name VARCHAR(100) NOT NULL,
company_country VARCHAR(50) NOT NULL
);

CREATE TABLE YASH_Televisions (


television_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
start_year INT NOT NULL,
head_office VARCHAR(100)
);

Q3 - Create an SQL statement to define a table named "Orders" with columns OrderID
(integer, primary key), CustomerID (integer), OrderDate (date), and Status (varchar(20)).
Ensure that the "CustomerID" column references the "Customers" table's
"CustomerID" as a foreign key.

CREATE TABLE YASH_Customer(


CustomerID
int primary key,
OrderID
int,
CustomerName
varchar(20)
);

CREATE
TABLE YASH_Orders(
OrderID
int primary key,
CustomerID
int,
OrderDate
date,
Status
varchar(20),
FOREIGN
KEY (CustomerID) references YASH_Customer(CustomerID)
);
INSERT INTO YASH_Customer(CustomerID, OrderID,CustomerName)
VALUES (1, 101,'JOHN');
INSERT INTO YASH_Customer(CustomerID, OrderID,CustomerName)
VALUES (2, 102,'ANSHIKA');
INSERT INTO YASH_Customer(CustomerID, OrderID,CustomerName)
VALUES (3, 103,'REEMA');
Update YASH_Customer SET OrderID = 1002
where CustomerName = 'ANSHIKA';
SELECT * FROM YASH_Customer;

1. Alter the name of your table using sp_rename command


EXEC sp_rename 'YASH_Customer', 'YASH_Client';

2. Retrieve all customer names from the table


SELECT CustomerName FROM
YASH_Customer;

3. Retrieve all order ids from the table


SELECT OrderNumber
FROM YASH_Orders;

4. All orders between two specific dates


SELECT *
FROM YASH_Orders
WHERE OrderDate BETWEEN '2024-01-23'AND '2024-03-23';

5. All orders which a particular customer has placed


SELECT *
FROM YASH_Orders
WHERE CustomerID = 1;
1. Write an SQL command to create a table named yourname_Employees with columns
EmployeeID, FirstName, LastName, and HireDate. Ensure that EmployeeID is a
primary key.

CREATE TABLE YASH_Employees (


EmployeeID INT PRIMARY KEY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
HireDate DATE
);

2. Demonstrate how to alter the Employees table to add a column Salary with a default
value.
ALTER TABLE YASH_Employees
ADD Salary DECIMAL(10, 2) DEFAULT 50000.00;

3. What is the difference between the DROP and TRUNCATE commands? Provide
examples.

DROP TABLE YASH_Students;


- After executing this command, the Students table no longer exists in the database.
TRUNCATE TABLE Students;
- After executing this command, the Students table will be empty but can still be used for
inserting new rows.

4. Write an SQL command to drop the Employees table from the database.

-- Drop the Employees table from the database


DROP TABLE YASH_Employees;

5. Write an SQL query to create a Books table with the following columns: BookID,
Title, Author, PublicationYear, and Price. Ensure that BookID is the primary key,
and Price cannot be negative.
CREATE TABLE YASH_Books (
BookID INT PRIMARY KEY,
Title NVARCHAR(100),
Author NVARCHAR(100),
PublicationYear INT,
Price DECIMAL(10, 2) CHECK (Price >= 0)
);

6. Add a column Genre to the existing Books table. The column should store the genre
of each book as a VARCHAR(50).
ALTER TABLE YASH_Books
ADD Genre VARCHAR(50);

7. Create a Borrowers table with a BorrowerID, Name, and BookID. Ensure that
BookID references the Books table, establishing a foreign key relationship.

CREATE TABLE YASH_Borrowers (


BorrowerID INT PRIMARY KEY, -- Unique identifier for each borrower
Name NVARCHAR(100), -- Name of the borrower (up to 100 characters)
BookID INT, -- ID of the book borrowed
FOREIGN KEY (BookID) REFERENCES YASH_Books(BookID) -- Establishes a foreign
key relationship with the Books table
);

8. Create a Students table with columns StudentID, FirstName, LastName, Age, and
Department. Ensure that:StudentID is the primary key. FirstName and LastName
cannot be null. Age must be between 18 and 35.

CREATE TABLE YASH_Students (


StudentID INT PRIMARY KEY,
FirstName NVARCHAR(50) NOT NULL,
LastName NVARCHAR(50) NOT NULL,
Age INT CHECK (Age BETWEEN 18 AND 35),
Department NVARCHAR(100)
);

9. Rename the Students table to UniversityStudents.


EXEC sp_rename 'Students', 'UniversityStudents';

10. Insert the following records into yourname_ Books table:

BookID: 1, Title: 'SQL Mastery', Author: 'John Doe', PublicationYear: 2020, Price: 49.99
BookID: 2, Title: 'Database Design', Author: 'Jane Doe', PublicationYear: 2018, Price: 39.99

INSERT INTO YASH_Books (BookID, Title, Author, PublicationYear, Price, Genre)


VALUES
(1, 'SQL Mastery', 'John Doe', 2020, 49.99, 'Technology'),
(2, 'Database Design', 'Jane Doe', 2018, 39.99, 'Technology');

11. Update the price of the book titled 'SQL Mastery' to 45.99.

UPDATE YASH_Books
SET Price = 45.99
WHERE Title = 'SQL Mastery';

12. Delete the record for the book titled 'Database Design'.

DELETE FROM YASH_Books


WHERE Title = 'Database Design';
13. Select all the books published after 2019 and priced under 50.

SELECT *
FROM YASH_Books
WHERE PublicationYear > 2019 AND Price < 50;

14. Create a table ‘yourname_employee_advanced’ with the following attributes:


emp_id, emp_name, Emp_joining_date.

CREATE TABLE YASH _employee_advanced (


emp_id INT PRIMARY KEY, -- Employee ID, set as the primary key
emp_name NVARCHAR(100) NOT NULL, -- Employee name, cannot be NULL
emp_joining_date DATE -- Employee joining date
);

15. Now add a new column ‘dept_id’ to the employee_advanced table -> this column
indicates the department to which this employee belongs.

ALTER TABLE YASH_employee_advanced


ADD dept_id INT;

16. Next, create a new table ‘department’. It should have the following attributes and
respective types: department_id int, department_name varchar(20),
department_starting_date date.

CREATE TABLE YASH_department (


department_id INT PRIMARY KEY,
department_name VARCHAR(20) NOT NULL,
department_starting_date DATE
);

17. The department_id of the ‘employee_advanced’ table should be the foreign key to
the department_id of the department table ( Hint : you might get some errors while
performing this step, you will need to write additional steps to get this done). Do take
a note of the errors encountered and the list of steps you took
to recover from this error.

Adding foreign key constraint --


ALTER TABLE yourname_employee_advanced
ADD CONSTRAINT FK_DeptID
FOREIGN KEY (dept_id) REFERENCES department(department_id);
JOINS
Ques 1 - Write insert statements to add the data per the screenshot shared above.

CREATE TABLE YASH_Emp(


Empno INT PRIMARY KEY,
EName VARCHAR(30),
Job VARCHAR(30),
MGR INT,
HireDate DATE,
Sal DECIMAL(10,2),
COMM DECIMAL(10,2),
DeptNo INT
);

ALTER TABLE YASH_Emp


ADD CONSTRAINT BK_DeptNo FOREIGN KEY (DeptNo)
REFERENCES YASH_Dept(DeptNo);

INSERT INTO YASH_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-03', 3000, NULL, 20),
(7934, 'Miller', 'Clerk', 7782, '1982-01-23', 1300, NULL, 10);

SELECT * FROM YASH_Emp;

CREATE TABLE YASH_Dept(


DeptNo INT PRIMARY KEY,
DName VARCHAR(30),
LOC VARCHAR(30)
);

SELECT * FROM YASH_Dept;


INSERT INTO YASH_Dept (DeptNo, Dname, LOC)
VALUES
(20, 'Research', 'Dallas'),
(10, 'Accounting', 'New York'),
(30, 'Sales', 'Chicago'),
(40, 'Operations', 'Boston');

-- Create the table Grade


CREATE TABLE YASH_Grade (
Grade INT,
Losal INT,
HISAL INT
);

-- Insert the data into the Grade table


INSERT INTO YASH_Grade(Grade, Losal, HISAL)
VALUES
(1, 700, 1200),
(2, 1201, 1400),
(3, 1401, 2000),
(4, 2001, 3000),
(5, 3001, 9999);

SELECT * FROM YASH_Grade;

Ques 2 - Write a query to display the job, department number, and department name
for all employees.

SELECT YASH_Emp.Job , YASH_Emp.DeptNo, YASH_Dept.DName


FROM YASH_Emp INNER JOIN YASH_Dept ON YASH_Emp.DeptNo =
YASH_Dept.DeptNo;

QUES 3 - Create a unique listing of all jobs that are in department 30. Include the
location of the department in the output.

SELECT DISTINCT YASH_Emp.Job , YASH_Dept.LOC


FROM YASH_Emp INNER JOIN YASH_Dept ON YASH_Emp.DeptNo =
YASH_Dept.DeptNo
WHERE YASH_Dept.DeptNo = 30;

QUES 4 - Write a query to display the employee name, department name, location
and job name of all employees who earn a commission.

SELECT YASH_Emp.EName , YASH_Dept.DName, YASH_Dept.LOC, YASH_Emp.Job


FROM YASH_Emp INNER JOIN YASH_Dept ON YASH_Emp.DeptNo =
YASH_Dept.DeptNo
WHERE YASH_Emp.COMM IS NOT NULL AND YASH_Emp.COMM > 0;

QUES 5 - Display the employee name and department name for all employees who
have an a in their names.

SELECT YASH_Emp.EName, YASH_Dept.DName


FROM YASH_Emp INNER JOIN YASH_Dept ON YASH_Emp.DeptNo =
YASH_Dept.DeptNo
WHERE YASH_Emp.EName LIKE '%a%';
QUES 6 - Display the employee name and employee number along with their
manager’s name and manager number. Label the columns Employee, Emp#,
Manager, and Mgr#, respectively.

SELECT YASH_Emp.EName AS Employee , YASH_Emp.Empno AS [Emp#], M.EName


AS Manager, M.Empno AS [Mgr#]
FROM YASH_Emp
LEFT JOIN YASH_Emp M ON YASH_Emp.MGR = M.Empno;
QUES 7 - Write a query to display the emp name, mgr name, job, department
number, and department name for all employees who work in Dallas.

SELECT YASH_Emp.EName, M.EName AS ManagerName , YASH_Emp.Job,


YASH_Emp.DeptNo, YASH_Dept.DName
FROM YASH_Emp
LEFT JOIN YASH_Emp M ON YASH_Emp.MGR = M.Empno
INNER JOIN YASH_Dept ON YASH_Emp.DeptNo = YASH_Dept.DeptNo
WHERE YASH_Dept.LOC = 'Dallas';

QUES 8 - Share the Department name who do not have any employees.

SELECT YASH_Dept.DName AS DEPARTMENT_NAME


FROM YASH_Dept
LEFT JOIN YASH_Emp ON YASH_Dept.DeptNo = YASH_Emp.DeptNo
WHERE YASH_Emp.Empno IS NULL;

Based on the employee table (having empid as PK, empname,


deptid and salary)

Q1. Count no. of employees in each department


SELECT deptid, COUNT(*) AS EmployeeCount
FROM YASH_EmployeeTable
GROUP BY deptid;

Q2. Min and Max salary of each department

SELECT deptid, MIN(salary) AS MinSalary, MAX(salary) AS MaxSalary


FROM YASH_EmployeeTable
GROUP BY deptid;

Q3. Find out the details of employee who gets the min salary out of all employees

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

Q4. Display departments having at least 2 employees

SELECT deptid
FROM YASH_EmployeeTable
GROUP BY deptid
HAVING COUNT(*) >= 2;

Q5. Write an SQL query to find the total sales for each product category from a sales
table containing product_id, category, and amount_sold.

SELECT category, SUM(amount_sold) AS TotalSales


FROM Sales
GROUP BY category;

Q6. Using an employees table containing employee_id, department_id, and salary,


write a query to count the number of employees in each department.

SELECT DeptNo , COUNT(Empno) AS EmployeeCount


FROM YASH_Emp
GROUP BY DeptNo;

Q7. Write a query to calculate the average salary for each department using the
employees table.

SELECT DeptNo, AVG(salary) AS AverageSalary


FROM YASH_Emp
GROUP BY DeptNo;
Q8. Given a sales table containing sale_id, category, amount_sold, and sale_date,
find the total revenue by year and category.

SELECT YEAR(sale_date) AS SaleYear, category, SUM(amount_sold) AS TotalRevenue


FROM Sales
GROUP BY YEAR(sale_date), category;

Q9. Write a query to find the maximum and minimum salary in each department
using the employees table.

SELECT DeptNo , MAX(salary) AS MaxSalary, MIN(salary) AS MinSalary


FROM YASH_Emp
GROUP BY DeptNo;

Q10. Using a sales table with product_id, category, and amount_sold, write a query
to find the top-selling product (the one with the highest amount_sold) in each
category.

WITH TopSelling AS (
SELECT category, product_id, SUM(amount_sold) AS TotalSold
FROM Sales
GROUP BY category, product_id
)
SELECT category, product_id, TotalSold
FROM (
SELECT category, product_id, TotalSold,
RANK() OVER (PARTITION BY category ORDER BY TotalSold DESC) AS Rank
FROM TopSelling
) AS Ranked
WHERE Rank = 1;

Q11. Write a query that returns the departments that have more than 5 employees.

SELECT department_id
FROM YASH_EmployeeTable
GROUP BY department_id
HAVING COUNT(employee_id) > 5;

SUB QUERIES
USING NESTED QUERY :

Q1. Write a query to display employee details (use emp table you created today) who
have the maximum salary.

SELECT *
FROM YASH_Emp
WHERE salary = (SELECT MAX(salary) FROM YASH_Emp);

Q2. Write a query to find all products whose price is higher than the average price in
the products table. (you can assume product table contains product id, product name
and price).

SELECT product_id, product_name, price


FROM products
WHERE price > (SELECT AVG(price) FROM products);

Q3. Write a query to find all orders placed by a customer named 'John Doe' using the
orders and customers tables. Assume order details are in one table and customer
details are in second table. The orders table does contain a mapping that which
customer has placed which order and its detail. ( do this question without joins).

SELECT *
FROM YASH_Orders
WHERE customer_id = (
SELECT customer_id
FROM YASH_Customers
WHERE customer_name = 'John Doe'
);

Q4. Write a query to find employees who earn more than the average salary of their
department in the employees table.

SELECT e.Empno,e.DeptNo,e.Sal
FROM YASH_Emp e
WHERE e.Sal > (SELECT AVG(Sal) FROM YASH_Emp WHERE DeptNo = e.DeptNo);
JOINS
Q1. Create below tables and insert the dataset as shared below.

1. Salesman

2. Customer

3. Orders

CREATE TABLE YASH_230732_SALESMAN(


salesman_id INT PRIMARY KEY,
name VARCHAR(50),
city VARCHAR(50),
commission DECIMAL(4, 2)
);
INSERT INTO YASH_230732_SALESMAN (salesman_id, name, city, commission)
VALUES
(5001, 'James Hoog', 'New York', 0.15),
(5002, 'Nail Knite', 'Paris', 0.13),
(5005, 'Pit Alex', 'London', 0.11),
(5006, 'Mc Lyon', 'Paris', 0.14),
(5007, 'Paul Adam', 'Rome', 0.13),
(5003, 'Lauson Hen', 'San Jose', 0.12);

SELECT * FROM YASH_230732_SALESMAN;

CREATE TABLE YASH_230732_CUSTOMER (


customer_id INT PRIMARY KEY,
cust_name VARCHAR(50),
city VARCHAR(50),
grade INT,
salesman_id INT,
FOREIGN KEY (salesman_id) REFERENCES YASH_230732_SALESMAN(salesman_id)
);

INSERT INTO YASH_230732_CUSTOMER (customer_id, cust_name, city, grade, salesman_id)


VALUES
(3002, 'Nick Rimando', 'New York', 100, 5001),
(3007, 'Brad Davis', 'New York', 200, 5001),
(3005, 'Graham Zusi', 'California', 200, 5002),
(3008, 'Julian Green', 'London', 300, 5002),
(3004, 'Fabian Johnson', 'Paris', 300, 5006),
(3009, 'Geoff Cameron', 'Berlin', 100, 5003),
(3003, 'Jozy Altidore', 'Moscow', 200, 5007);

INSERT INTO dbo.YASH_230732_CUSTOMER (customer_id, cust_name, city, grade,


salesman_id)
VALUES (3001, 'Julian Davis ', ' Berlin ', 100, 5001);

SELECT * FROM YASH_230732_CUSTOMER;

CREATE TABLE YASH_230732_ORDERS (


ord_no INT PRIMARY KEY,
purch_amt DECIMAL(10, 2),
ord_date DATE,
customer_id INT,
salesman_id INT,
FOREIGN KEY (customer_id) REFERENCES YASH_230732_CUSTOMER(customer_id),
FOREIGN KEY (salesman_id) REFERENCES YASH_230732_SALESMAN(salesman_id)
);

insert into YASH_230732_ORDERS values (70001, 150.5, '2012-10-05', 3005, 5002);


insert into YASH_230732_ORDERS values (70009, 270.65, '2012-09-10' ,3001, 5005);
insert into YASH_230732_ORDERS values (70002, 65.26, '2012-10-05', 3002, 5001);
insert into YASH_230732_ORDERS values (70004, 110.5, '2012-08-17', 3009, 5003);
insert into YASH_230732_ORDERS values (70007, 948.5, '2012-09-10', 3005, 5002);
insert into YASH_230732_ORDERS values (70005, 2400.6, '2012-07-27', 3007, 5001);
insert into YASH_230732_ORDERS values (70008, 5760, '2012-09-10', 3002, 5001);

--DELETE FROM YASH_230732_ORDERS;

SELECT * FROM YASH_230732_ORDERS;

1. Write a query to provide total order value by Salesman city for all the orders sold in
Sept and Oct month. Max Order value should be at the top.
SELECT
S.city AS SalesmanCity,
SUM(O.purch_amt) AS TotalOrderValue
FROM
YASH_230732_ORDERS O
JOIN
YASH_230732_SALESMAN S
ON
O.salesman_id = S.salesman_id
WHERE
MONTH(O.ord_date) IN (9, 10) -- Filters for September (9) and October (10)
AND YEAR(O.ord_date) = 2012 -- Adjust the year if needed
GROUP BY
S.city
ORDER BY
TotalOrderValue DESC; -- Sort by total order value in descending order

2. Write a query to give the Salesman details who haven’t sold any orders.
SELECT
S.salesman_id,
S.name,
S.city,
S.commission
FROM
YASH_230732_SALESMAN S
LEFT JOIN
YASH_230732_ORDERS O
ON
S.salesman_id = O.salesman_id
WHERE
O.salesman_id IS NULL; -- This ensures we only get salesmen with no orders
3. Write a query to get the customer details whose city is not same as Salesman city. (Do
not use values from Salesman table to filter customer table. It should be dynamic and
should work in case there is new data in Salesman table)
SELECT
C.customer_id,
C.cust_name,
C.city AS CustomerCity,
S.city AS SalesmanCity,
C.grade,
C.salesman_id
FROM
YASH_230732_CUSTOMER C
JOIN
YASH_230732_SALESMAN S
ON
C.salesman_id = S.salesman_id
WHERE
C.city <> S.city; -- Filter customers whose city is not the same as the salesman's city

4. Write a SQL query to apply a check constraint on Salesman’s commission.


Commission should not be less than 0.15 in Salesman table. If there is any error, take
appropriate steps to fix it, either by increasing the commission to min value shared
above.
ALTER TABLE YASH_230732_SALESMAN
ADD CONSTRAINT c_commission
CHECK (commission >= 0.15);

UPDATE YASH_230732_SALESMAN
SET commission = 0.15
WHERE commission < 0.15;

SELECT * FROM YASH_230732_SALESMAN


WHERE commission < 0.15;
5. Write a SQL unique constraint to be applied on Salesman table. It should be applied on
Salesman’s city column. If there is any duplicate, assign it to the city as found out in SQL
query #3.
--This query will return cities that have more than one salesman.
SELECT city , COUNT(*) AS duplicate
FROM YASH_230732_SALESMAN
GROUP BY city
HAVING COUNT(*) > 1;

-- Assume we want to update any duplicates to 'New City' temporarily.


UPDATE YASH_230732_SALESMAN
SET city = 'New City'
WHERE salesman_id IN (
SELECT salesman_id
FROM (
SELECT salesman_id, ROW_NUMBER() OVER (PARTITION BY city ORDER BY
salesman_id) AS row_num
FROM YASH_230732_SALESMAN
) AS temp
WHERE temp.row_num > 1 -- Select duplicates only (2nd, 3rd, etc.)
);

ALTER TABLE YASH_230732_SALESMAN


ADD CONSTRAINT uq_salesman_city UNIQUE (city);
VIEWS

EXAMPLE 
CREATE VIEW YASH_EMP_VIEW AS
SELECT Empno,Ename ,Job FROM YASH_Emp
WHERE DeptNo = 20;

INSERT INTO YASH_EMP_VIEW (Empno, Ename,Job) VALUES (80002,'Zoya','Manager');

select * from YASH_EMP_VIEW;

CREATE VIEW YASH_230732_SALESMAN_VIEW AS


SELECT *
FROM YASH_230732_SALESMAN
WHERE city = 'New York' AND commission >= 0.15;
select * from YASH_230732_SALESMAN_VIEW;
CREATE VIEW YASH_Customer_Count AS
SELECT grade, COUNT(*) AS customer_count
FROM YASH_230732_CUSTOMER
GROUP BY grade;
SELECT * FROM YASH_Customer_Count;

CREATE TABLE Students_Payment_230732 (


first_name NVARCHAR(50),
last_name NVARCHAR(50),
course NVARCHAR(50),
amount_paid INT
);

INSERT INTO Students_Payment_230732 (first_name, last_name, course, amount_paid)


VALUES
('Luisa', 'Evans', 'Java', 20000),
('Peter', 'Bennett', 'Python', 18000),
('Rose', 'Huges', 'Machine Learning', 30000),
('Antonio', 'Butler', 'Android', 22000),
('Diego', 'Cox', 'SQL', 15000);

INSERT INTO Students_Payment_230732 (first_name, last_name, course, amount_paid)


VALUES
('Antio', 'Butter', 'Android', 72000),
('Digo', 'Cex', 'SQL', 17000);

SELECT * FROM Students_Payment_230732;

--creating a view ->


CREATE VIEW YASH_course_view
AS
SELECT first_name, course FROM Students_Payment_230732
WHERE amount_paid > 19000;

UPDATE Students_Payment_230732
SET amount_paid = 29000
WHERE first_name = 'RIYA';

SELECT * FROM YASH_course_view;


INSERT INTO YASH_course_view(first_name,course) VALUES ('RIYA', 'MACHINE
LEARNING');
CREATE VIEW YASH_VIEW_AMTPAID
AS SELECT first_name, course, amount_paid
FROM Students_Payment_230732
WHERE amount_paid >= 18000;

EXEC sp_rename 'YASH_VIEW_AMTPAID' , 'YASHVIEW_AMT_PAID';


SELECT * FROM YASHVIEW_AMT_PAID;
FUNCTIONS

1. Write a query to display the job, department number, and department name for all
employees.
CREATE FUNCTION YASH_GetJobDeptDetails()
RETURNS TABLE
AS
RETURN
(
SELECT e.Job, d.DeptNo, d.DName
FROM YASH_Emp e
JOIN YASH_Dept d ON e.DeptNo = d.DeptNo
);
SELECT * FROM YASH_GetJobDeptDetails();
2. Create a unique listing of all jobs that are in department 30. Include the location of the
department in the output.

CREATE FUNCTION YASH_GetUniqueJobsDept30()


RETURNS TABLE
AS
RETURN
(
SELECT DISTINCT e.Job,d.LOC
FROM YASH_Emp e
JOIN YASH_Dept d ON e.DeptNo = d.DeptNo
WHERE e.DeptNo = 30
);
SELECT * FROM YASH_GetUniqueJobsDept30();

3. Write a query to display the employee’s name, department name, location and job
name of all employees who earn a commission.

CREATE FUNCTION YASH_GetEmployeesWithCommission()


RETURNS TABLE
AS
RETURN
(
SELECT e.EName, d.DName, d.LOC , e.Job
FROM YASH_Emp e
JOIN YASH_Dept d ON e.DeptNo = d.DeptNo
WHERE e.COMM IS NOT NULL
);
SELECT * FROM YASH_GetEmployeesWithCommission();
4. Display the employee name and department name for all employees who have an a in
their names.

CREATE FUNCTION YASH_GetEmployeesWithAInName()


RETURNS TABLE
AS
RETURN
(
SELECT e.EName, d.DName
FROM YASH_Emp e
JOIN YASH_Dept d ON e.DeptNo = d.DeptNo
WHERE e.EName LIKE '%a%'
);

SELECT * FROM YASH_GetEmployeesWithAInName();

5. Display the employee name and employee number along with their manager’s name
and manager number. Label the columns Employee, Emp#, Manager, and Mgr#,
respectively.

CREATE FUNCTION YASH_GetEmpManagerDetails()


RETURNS TABLE
AS
RETURN
(
SELECT
e1.EName AS Employee,
e1.Empno AS Emp#,
e2.EName AS Manager,
e2.Empno AS Mgr#
FROM YASH_Emp e1
LEFT JOIN YASH_Emp e2 ON e1.MGR = e2.Empno
);
SELECT * FROM YASH_GetEmpManagerDetails();

6. Write a query to display the emp name, mgr name, job, department number, and
department name for all employees who work in Dallas.

CREATE FUNCTION YASH_GetEmpInDallas()


RETURNS TABLE
AS
RETURN
(
SELECT
e.EName,
m.EName AS mgrname,
e.Job,
d.DeptNo,
d.DName
FROM YASH_Emp e
LEFT JOIN YASH_Emp m ON e.MGR = m.Empno
JOIN YASH_Dept d ON e.deptno = d.DeptNo
WHERE d.LOC = 'Dallas'
);

SELECT * FROM YASH_GetEmpInDallas();

7. Share the Department name who do not have any employees.

CREATE FUNCTION YASH_GetEmptyDepartments()


RETURNS TABLE
AS
RETURN
(
SELECT d.DName
FROM YASH_Dept d
LEFT JOIN YASH_Emp e ON d.DeptNo = e.DeptNo
WHERE e.Empno IS NULL
);
SELECT * FROM YASH_GetEmptyDepartments();
STORED PROCEDURES
EXAMPLE 
SELECT * FROM YASHYadav_Students;
CREATE PROCEDURE YASH_STUDENTLIST
AS
BEGIN
SELECT NAME, Age
FROM YASHYadav_Students
ORDER BY DOB;
END;

-- ALTER PROCEDURE
ALTER PROCEDURE YASH_STUDENTLIST
AS
BEGIN
SET NOCOUNT ON
SELECT NAME,Age
FROM YASHYadav_Students
ORDER BY Age;
END;

EXEC YASH_STUDENTLIST;
Q1. Create a stored procedure to retrieve customers who are being serviced by a salesman
with the name 'James Hoog’.
CREATE PROCEDURE YASH_SP_VAR @city VARCHAR(100), @salesman_id INT AS
BEGIN
SELECT * FROM YASH_230732_SALESMAN WHERE city = @city
SELECT * FROM YASH_230732_SALESMAN WHERE salesman_id = @salesman_id
END;
EXEC YASH_SP_VAR @City = 'NEW YORK', @salesman_id = 5001;

-- alter procedure to retrieve customers who are being serviced by a salesman called 'James hoog'

SELECT * FROM YASH_230732_CUSTOMER;


SELECT * FROM YASH_230732_SALESMAN;

ALTER PROCEDURE YASH_SP_VAR


@City VARCHAR(100),
@salesman_id INT
AS
BEGIN
-- Select customers serviced by salesman named 'James Hoog'
SELECT c.*
FROM YASH_230732_CUSTOMER c
INNER JOIN YASH_230732_SALESMAN s ON c.salesman_id = s.salesman_id
WHERE s.name = 'James Hoog';

-- Original queries with parameters


SELECT * FROM YASH_230732_SALESMAN WHERE city = @city;
SELECT * FROM YASH_230732_SALESMAN WHERE salesman_id = @salesman_id;
END;
Q2. Create a stored procedure to get a list of all salesmen along with their customers.
CREATE PROCEDURE YASH_GetSalesmanWithCustomers
AS
BEGIN
SELECT s.salesman_id , s.name, c.customer_id , c.cust_name
FROM YASH_230732_SALESMAN s
LEFT JOIN YASH_230732_CUSTOMER c ON s.salesman_id = c.salesman_id
ORDER BY s.name;
END;

EXEC YASH_GetSalesmanWithCustomers;
Q3. Create a dynamic stored procedure to add a new salesman to the salesman table.

CREATE PROCEDURE YASH_InsertNewSalesman


@name NVARCHAR(100),
@city NVARCHAR(100),
@commission DECIMAL(5, 2)
AS
BEGIN
DECLARE @sql NVARCHAR(MAX);

SET @sql = N'


INSERT INTO YASH_230732_SALESMAN (salesman_id,name, city, commission)
VALUES (@salesman_id,@name, @city, @commission);
';

EXEC sp_executesql
@sql,
N'@salesman_id ,@name NVARCHAR(100), @city NVARCHAR(100), @commission
DECIMAL(5, 2)',
@name = @name,
@city = @city,
@commission = @commission;
END;
alter procedure YASH_InsertNewSalesman @SALESMAN_ID INT, @NAME
VARCHAR(100), @CITY VARCHAR(50) , @COMMISSION DECIMAL(5,2) as
begin
INSERT INTO YASH_230732_SALESMAN(salesman_id, name, City,
Commission)
VALUES (@SALESMAN_ID , @NAME, @CITY, @COMMISSION)
end

EXECUTE YASH_InsertNewSalesman @SALESMAN_ID = 50001 , @NAME = 'Rhea


Yadav' , @CITY = 'varanasi' , @COMMISSION = 2.15;
Q4. Create a dynamic sp to update the city of a particular salesman.
CREATE PROCEDURE YASH_UpdateSalesmanCity
@salesman_id INT,
@city NVARCHAR(100)
AS
BEGIN
DECLARE @sql NVARCHAR(MAX);

-- Construct the dynamic SQL query


SET @sql = N'
UPDATE YASH_230732_SALESMAN
SET city = @city
WHERE salesman_id = @salesman_id;
';

-- Execute the dynamic SQL with parameter mapping


EXEC sp_executesql
@sql,
N'@salesman_id INT, @city NVARCHAR(100)',
@salesman_id = @salesman_id,
@city = @city;
END;

EXEC YASH_UpdateSalesmanCity
@salesman_id = 5005,
@city = 'Mumbai';

SELECT * FROM YASH_230732_SALESMAN;


Q5. Create a dynamic stored procedure to remove a customer by ID. Will it execute
conceptually?
SELECT * FROM YASH_230732_CUSTOMER;

CREATE PROCEDURE YASH_RemoveCustomerByID


@customer_id INT
AS
BEGIN
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'
DELETE FROM YASH_230732_CUSTOMER
WHERE customer_id = @customer_id
';
EXEC sp_executesql
@sql,
N'@customer_id INT',
@customer_id = @customer_id;

END;
EXEC YASH_RemoveCustomerByID @customer_id = 3008;
SELECT * FROM YASH_230732_CUSTOMER;

Q6. Create a dynamic stored procedure to remove a salesman by ID. Will it execute conceptually?

SELECT * FROM YASH_230732_SALESMAN;


CREATE PROCEDURE YASH_RemoveSalesmanByID
@salesman_id INT
AS
BEGIN
DECLARE @sql NVARCHAR(MAX);

-- Construct the dynamic SQL query


SET @sql = N'
DELETE FROM YASH_230732_SALESMAN
WHERE salesman_id = @salesman_id;
';

-- Execute the dynamic SQL with parameter mapping


EXEC sp_executesql
@sql,
N'@salesman_id INT',
@salesman_id = @salesman_id;
END;
EXEC YASH_RemoveSalesmanByID @salesman_id = 5004;
SELECT * FROM YASH_230732_SALESMAN;

Q7. Create a dynamic stored procedure to get Salesmen with the minimum number of
customers.
CREATE PROCEDURE YASH_GetSalesmenWithMinCustomers
AS
BEGIN
DECLARE @sql NVARCHAR(MAX);
-- Construct the dynamic SQL query
SET @sql = N'
SELECT S.salesman_id, S.name, COUNT(C.customer_id) AS customer_count
FROM YASH_230732_CUSTOMER AS C
INNER JOIN YASH_230732_SALESMAN AS S ON C.salesman_id = S.salesman_id
GROUP BY S.salesman_id, S.name
HAVING COUNT(C.customer_id) = (
SELECT MIN(customer_count)
FROM (
SELECT COUNT(customer_id) AS customer_count
FROM YASH_230732_CUSTOMER
GROUP BY salesman_id
) AS counts
);
';

-- Execute the dynamic SQL


EXEC sp_executesql @sql;
END;
EXEC YASH_GetSalesmenWithMinCustomers;

You might also like