Dbms Lab Report - 230709
Dbms Lab Report - 230709
TECHNOLOGY
B.TECH. COMPUTER SCIENCE &
ENGINEERING
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).
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_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;
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.
4. Write an SQL command to drop the Employees table from the database.
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.
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.
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
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'.
SELECT *
FROM YASH_Books
WHERE PublicationYear > 2019 AND Price < 50;
15. Now add a new column ‘dept_id’ to the employee_advanced table -> this column
indicates the department to which this employee belongs.
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.
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.
Ques 2 - Write a query to display the job, department number, and department name
for all employees.
QUES 3 - Create a unique listing of all jobs that are in department 30. Include the
location of the department in the output.
QUES 4 - Write a query to display the employee name, department name, location
and job name of all employees who earn a commission.
QUES 5 - Display the employee name and department name for all employees who
have an a in their names.
QUES 8 - Share the Department name who do not have any employees.
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);
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.
Q7. Write a query to calculate the average salary for each department using the
employees table.
Q9. Write a query to find the maximum and minimum salary in each department
using the employees table.
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).
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
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
UPDATE YASH_230732_SALESMAN
SET commission = 0.15
WHERE commission < 0.15;
EXAMPLE
CREATE VIEW YASH_EMP_VIEW AS
SELECT Empno,Ename ,Job FROM YASH_Emp
WHERE DeptNo = 20;
UPDATE Students_Payment_230732
SET amount_paid = 29000
WHERE first_name = 'RIYA';
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.
3. Write a query to display the employee’s name, department name, location and job
name of all employees who earn a commission.
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.
6. Write a query to display the emp name, mgr name, job, department number, and
department name for all employees who work in Dallas.
-- 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'
EXEC YASH_GetSalesmanWithCustomers;
Q3. Create a dynamic stored procedure to add a new salesman to the salesman table.
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
EXEC YASH_UpdateSalesmanCity
@salesman_id = 5005,
@city = 'Mumbai';
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?
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
);
';