0% found this document useful (0 votes)
314 views26 pages

JOINS

The document contains examples of using SQL joins to retrieve data from multiple tables. It demonstrates basic join types like inner joins, left joins, retrieving data from related tables using primary and foreign keys. It also shows aggregation functions like count, sum with group by to retrieve aggregated data from related tables. A total of 5 practices with sample table structures, data and SQL queries are shown to retrieve and combine data from related tables in different ways using joins.

Uploaded by

karthicksystech0
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)
314 views26 pages

JOINS

The document contains examples of using SQL joins to retrieve data from multiple tables. It demonstrates basic join types like inner joins, left joins, retrieving data from related tables using primary and foreign keys. It also shows aggregation functions like count, sum with group by to retrieve aggregated data from related tables. A total of 5 practices with sample table structures, data and SQL queries are shown to retrieve and combine data from related tables in different ways using joins.

Uploaded by

karthicksystech0
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/ 26

JOINS:-

PRACTICE 1

-- Create Employees table


CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DepartmentID INT
);

-- Insert data into Employees table


INSERT INTO Employees (EmployeeID, FirstName, LastName, DepartmentID)
VALUES (1, 'John', 'Doe', 1),
(2, 'Jane', 'Smith', 2),
(3, 'Bob', 'Johnson', 1),
(4, 'Alice', 'Williams', 3);

-- Create Departments table


CREATE TABLE Departments (
DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(50)
);

-- Insert data into Departments table


INSERT INTO Departments (DepartmentID, DepartmentName)
VALUES (1, 'IT'),
(2, 'HR'),
(3, 'Finance');

Questions:-
-- Question 1: Retrieve all employees with their department names
-- Question 2: Retrieve employees and their department names, including those without a
Department
-- Question 3: Retrieve the total number of employees in each department
-- Question 1: Retrieve all employees with their department names

SELECT e.EmployeeID, e.FirstName, e.LastName, d.DepartmentName


FROM Employees e
JOIN Departments d ON e.DepartmentID = d.DepartmentID;

-- Question 2: Retrieve employees and their department names, including those without a
Department

SELECT e.EmployeeID, e.FirstName, e.LastName, COALESCE(d.DepartmentName, 'No Department')


AS DepartmentName
FROM Employees e
LEFT JOIN Departments d ON e.DepartmentID = d.DepartmentID;

-- Question 3: Retrieve the total number of employees in each department

SELECT d.DepartmentName, COUNT(e.EmployeeID) AS EmployeeCount


FROM Departments d
LEFT JOIN Employees e ON d.DepartmentID = e.DepartmentID
GROUP BY d.DepartmentName;
PRACTISE 2
-- Create a new table: Projects
CREATE TABLE Projects (
ProjectID INT PRIMARY KEY,
ProjectName VARCHAR(50),
DepartmentID INT
);

-- Insert data into Projects table


INSERT INTO Projects (ProjectID, ProjectName, DepartmentID)
VALUES (101, 'Project A', 1),
(102, 'Project B', 2),
(103, 'Project C', 1);

Questions:-
-- Question 1: Retrieve employees with their department names and the projects they are working
on
-- Question 2: Retrieve the total number of employees and the total number of projects in each
department
-- Question 1: Retrieve employees with their department names and the projects they are working
on

SELECT e.EmployeeID, e.FirstName, e.LastName, d.DepartmentName, p.ProjectName


FROM Employees e
JOIN Departments d ON e.DepartmentID = d.DepartmentID
LEFT JOIN Projects p ON e.DepartmentID = p.DepartmentID;

-- Question 2: Retrieve the total number of employees and the total number of projects in each
department

SELECT d.DepartmentName, COUNT(DISTINCT e.EmployeeID) AS EmployeeCount, COUNT(DISTINCT


p.ProjectID) AS ProjectCount
FROM Departments d
LEFT JOIN Employees e ON d.DepartmentID = e.DepartmentID
LEFT JOIN Projects p ON d.DepartmentID = p.DepartmentID
GROUP BY d.DepartmentName;
PRACTISE 3
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Email VARCHAR(100)
);

CREATE TABLE Orders (


OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE,
TotalAmount DECIMAL(10, 2),
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

-- Insert data into Customers table


INSERT INTO Customers (CustomerID, FirstName, LastName, Email)
VALUES
(1, 'John', 'Doe', '[email protected]'),
(2, 'Jane', 'Smith', '[email protected]'),
(3, 'Bob', 'Johnson', '[email protected]');

-- Insert data into Orders table


INSERT INTO Orders (OrderID, CustomerID, OrderDate, TotalAmount)
VALUES
(101, 1, '2023-01-05', 150.50),
(102, 1, '2023-02-10', 75.25),
(103, 2, '2023-03-15', 200.00),
(104, 3, '2023-04-20', 50.75);

Questions:-

1.List all orders with customer details (first name, last name) for each order.
2.Find the total amount spent by each customer. Include customers who haven't placed any orders.
3.List the customer names and email addresses for those who have placed orders in the year 2023.
4.Identify customers who have not placed any orders.
5.List the order details (order ID, order date, total amount) along with customer names for orders
placed in February 2023.
6.Find the average order amount for each customer. Include customers who haven't placed any
orders.
1.List all orders with customer details (first name, last name) for each order.

SELECT Orders.OrderID, Customers.FirstName, Customers.LastName, Orders.OrderDate,


Orders.TotalAmount
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

2.Find the total amount spent by each customer. Include customers who haven't placed any
orders.

SELECT Customers.CustomerID, Customers.FirstName, Customers.LastName,


COALESCE(SUM(Orders.TotalAmount), 0) AS TotalAmountSpent
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
GROUP BY Customers.CustomerID, Customers.FirstName, Customers.LastName;

3.List the customer names and email addresses for those who have placed orders in the year 2023.

SELECT DISTINCT Customers.FirstName, Customers.LastName, Customers.Email


FROM Customers
INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID
WHERE YEAR(Orders.OrderDate) = 2023;

4.Identify customers who have not placed any orders.

SELECT Customers.CustomerID, Customers.FirstName, Customers.LastName


FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
WHERE Orders.OrderID IS NULL;

5.List the order details (order ID, order date, total amount) along with customer names for orders
placed in February 2023.

SELECT Orders.OrderID, Orders.OrderDate, Orders.TotalAmount, Customers.FirstName,


Customers.LastName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID
WHERE YEAR(Orders.OrderDate) = 2023 AND MONTH(Orders.OrderDate) = 2;

6.Find the average order amount for each customer. Include customers who haven't placed any
orders.

SELECT Customers.CustomerID, Customers.FirstName, Customers.LastName,


COALESCE(AVG(Orders.TotalAmount), 0) AS AverageOrderAmount
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
GROUP BY Customers.CustomerID, Customers.FirstName, Customers.LastName;
PRACTISE 4
-- Create 'employees' table
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(255),
department_id INT,
salary DECIMAL(10, 2),
FOREIGN KEY (department_id) REFERENCES departments(department_id)
);

-- Create 'departments' table


CREATE TABLE departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(255)
);

-- Insert data into 'departments' table


INSERT INTO departments (department_id, department_name) VALUES
(1, 'HR'),
(2, 'Finance'),
(3, 'IT');

-- Insert data into 'employees' table


INSERT INTO employees (employee_id, employee_name, department_id, salary) VALUES
(1, 'John Doe', 1, 50000.00),
(2, 'Jane Smith', 2, 60000.00),
(3, 'Bob Johnson', 1, 55000.00),
(4, 'Alice Brown', 3, 70000.00),
(5, 'Charlie Davis', 2, 65000.00);

Questions:-

1.Question: Retrieve the names of employees along with their corresponding department names.
2.Question: List all departments and the names of employees (if any) in each department.
3.Question: Find the total salary of each department.
4.Question: Retrieve the names of employees, their department names, and the location of each
department.
5.Question: List the names of employees in the IT department who earn more than $60,000.
6.Question: Find pairs of employees who have the same manager (assuming a manager is also an
employee in the same table).
1.Question: Retrieve the names of employees along with their corresponding department names.
SELECT employees.employee_name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id;
Left Join with Null Values:

2.Question: List all departments and the names of employees (if any) in each department.

SELECT departments.department_name, employees.employee_name


FROM departments
LEFT JOIN employees ON departments.department_id = employees.department_id;
Aggregate Function with Join:

3.Question: Find the total salary of each department.

SELECT departments.department_name, SUM(employees.salary) as total_salary


FROM departments
LEFT JOIN employees ON departments.department_id = employees.department_id
GROUP BY departments.department_name;

4.Question: Retrieve the names of employees, their department names, and the location of each
department.

SELECT employees.employee_name, departments.department_name, departments.location


FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id;

5.Question: List the names of employees in the IT department who earn more than $60,000.

SELECT employees.employee_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id
WHERE departments.department_name = 'IT' AND employees.salary > 60000;

6.Question: Find pairs of employees who have the same manager (assuming a manager is also an
employee in the same table).

SELECT e1.employee_name AS employee1, e2.employee_name AS employee2


FROM employees e1
INNER JOIN employees e2 ON e1.manager_id = e2.manager_id
WHERE e1.employee_id < e2.employee_id;
PRACTISE 5
-- Create employees table
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(255),
emp_department VARCHAR(50),
emp_salary INT,
emp_manager_id INT
);

-- Insert data into employees table


INSERT INTO employees VALUES
(1, 'Alice', 'HR', 50000, NULL),
(2, 'Bob', 'IT', 60000, NULL),
(3, 'Charlie', 'Finance', 55000, NULL),
(4, 'David', 'Marketing', 52000, NULL);

-- Create departments table


CREATE TABLE departments (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(50),
dept_location VARCHAR(255)
);

-- Insert data into departments table


INSERT INTO departments VALUES
(101, 'HR', 'New York'),
(102, 'IT', 'San Francisco'),
(103, 'Finance', 'Chicago'),
(104, 'Marketing', 'Los Angeles');

Questions:-

1.Question: Display the names of employees along with the names of their managers. Assume that
the manager is also an employee in the same table and is identified by the emp_manager_id
column, which refers to the emp_id of the manager.

2.Question: Generate all possible combinations of employee names and department names,
regardless of whether there is a match between them.

3.Question: Display the names of employees who have a salary greater than the average salary of
employees in the IT department.
4.Question: List the names of employees and their corresponding department locations.
5.Question: Show a list of all employees and their salaries along with the department information. If
an employee is not assigned to any department, display "N/A" for department information.
6.Question: Display the department names and the names of employees belonging to those
departments. Include departments with no employees, displaying "No employees" for such cases.
7.Question: List all employees and their departments along with the department information. If an
employee or department has no match, display "Unassigned" for employees or "No employees" for
departments.
1.Question: Display the names of employees along with the names of their managers. Assume that
the manager is also an employee in the same table and is identified by the emp_manager_id
column, which refers to the emp_id of the manager.

SELECT e.emp_name AS employee_name, m.emp_name AS manager_name


FROM employees e
LEFT JOIN employees m ON e.emp_manager_id = m.emp_id;
Cross Join:

2.Question: Generate all possible combinations of employee names and department names,
regardless of whether there is a match between them.

SELECT emp_name, dept_name


FROM employees
CROSS JOIN departments;
Conditional Join:

3.Question: Display the names of employees who have a salary greater than the average salary of
employees in the IT department.

SELECT emp_name
FROM employees
INNER JOIN departments ON employees.emp_department = departments.dept_name
WHERE emp_salary > (SELECT AVG(emp_salary) FROM employees WHERE emp_department = 'IT');

4.Question: List the names of employees and their corresponding department locations.

SELECT emp_name, dept_location


FROM employees
INNER JOIN departments ON employees.emp_department = departments.dept_name;

5.Question: Show a list of all employees and their salaries along with the department information.
If an employee is not assigned to any department, display "N/A" for department information.

SELECT emp_name, emp_salary, COALESCE(dept_name, 'N/A') AS department


FROM employees
LEFT JOIN departments ON employees.emp_department = departments.dept_name;
Right Join:
6.Question: Display the department names and the names of employees belonging to those
departments. Include departments with no employees, displaying "No employees" for such cases.

SELECT COALESCE(emp_name, 'No employees') AS employee_name, dept_name


FROM employees
RIGHT JOIN departments ON employees.emp_department = departments.dept_name;

7.Question: List all employees and their departments along with the department information. If an
employee or department has no match, display "Unassigned" for employees or "No employees"
for departments.

SELECT COALESCE(emp_name, 'Unassigned') AS employee_name, COALESCE(dept_name, 'No


employees') AS department
FROM employees
FULL OUTER JOIN departments ON employees.emp_department = departments.dept_name;
PRACTISE 6
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50),
Salary DECIMAL(10, 2)
);

CREATE TABLE Attendance (


AttendanceID INT PRIMARY KEY,
EmployeeID INT,
AttendanceDate DATE,
StartTime TIME,
EndTime TIME,
CONSTRAINT FK_Employee_Attendance FOREIGN KEY (EmployeeID) REFERENCES
Employee(EmployeeID)
);

-- Inserting data into Employee table


INSERT INTO Employee (EmployeeID, FirstName, LastName, Department, Salary)
VALUES
(1, 'John', 'Doe', 'IT', 60000.00),
(2, 'Jane', 'Smith', 'HR', 55000.00),
(3, 'Bob', 'Johnson', 'Finance', 62000.00);

-- Inserting data into Attendance table


INSERT INTO Attendance (AttendanceID, EmployeeID, AttendanceDate, StartTime, EndTime)
VALUES
(1, 1, '2023-01-01', '09:00:00', '17:00:00'),
(2, 2, '2023-01-01', '08:30:00', '16:30:00'),
(3, 3, '2023-01-01', '10:00:00', '18:00:00');

Questions:-

1.Retrieve a list of employees with their attendance information (if available):


2List the total working hours for each employee on a specific date:
3. Retrieve a list of employees who have not recorded attendance on a given date:
4. List employees and their average working hours per day:
5. Retrieve a list of employees who have attended on all recorded dates:
6. Find employees with overlapping attendance on the same date:
7. List employees and the total number of days they have attended:
1.Retrieve a list of employees with their attendance information (if available):
SELECT
Employee.EmployeeID,
Employee.FirstName,
Employee.LastName,
Attendance.AttendanceDate,
Attendance.StartTime,
Attendance.EndTime
FROM Employee
LEFT JOIN Attendance ON Employee.EmployeeID = Attendance.EmployeeID;

2.List the total working hours for each employee on a specific date:

SELECT
Employee.EmployeeID,
Employee.FirstName,
Employee.LastName,
Attendance.AttendanceDate,
SUM(DATEDIFF(MINUTE, Attendance.StartTime, Attendance.EndTime)) AS TotalWorkingMinutes
FROM Employee
LEFT JOIN Attendance ON Employee.EmployeeID = Attendance.EmployeeID
WHERE Attendance.AttendanceDate = '2023-01-01'
GROUP BY Employee.EmployeeID, Employee.FirstName, Employee.LastName,
Attendance.AttendanceDate;

3. Retrieve a list of employees who have not recorded attendance on a given date:

SELECT
Employee.EmployeeID,
Employee.FirstName,
Employee.LastName
FROM Employee
LEFT JOIN Attendance ON Employee.EmployeeID = Attendance.EmployeeID
WHERE Attendance.EmployeeID IS NULL OR Attendance.AttendanceDate <> '2023-01-01';

4. List employees and their average working hours per day:

SELECT
Employee.EmployeeID,
Employee.FirstName,
Employee.LastName,
AVG(DATEDIFF(MINUTE, Attendance.StartTime, Attendance.EndTime)) AS
AverageWorkingMinutes
FROM Employee
LEFT JOIN Attendance ON Employee.EmployeeID = Attendance.EmployeeID
GROUP BY Employee.EmployeeID, Employee.FirstName, Employee.LastName;
5. Retrieve a list of employees who have attended on all recorded dates:

SELECT
Employee.EmployeeID,
Employee.FirstName,
Employee.LastName
FROM Employee
JOIN Attendance ON Employee.EmployeeID = Attendance.EmployeeID
GROUP BY Employee.EmployeeID, Employee.FirstName, Employee.LastName
HAVING COUNT(DISTINCT Attendance.AttendanceDate) = (SELECT COUNT(DISTINCT
AttendanceDate) FROM Attendance);

6. Find employees with overlapping attendance on the same date:

SELECT
e1.EmployeeID AS Employee1ID,
e1.FirstName AS Employee1FirstName,
e1.LastName AS Employee1LastName,
e2.EmployeeID AS Employee2ID,
e2.FirstName AS Employee2FirstName,
e2.LastName AS Employee2LastName,
a.AttendanceDate
FROM Employee e1
JOIN Employee e2 ON e1.EmployeeID < e2.EmployeeID
JOIN Attendance a ON e1.EmployeeID = a.EmployeeID AND e2.EmployeeID = a.EmployeeID AND
e1.AttendanceDate = a.AttendanceDate;

7. List employees and the total number of days they have attended:

SELECT
Employee.EmployeeID,
Employee.FirstName,
Employee.LastName,
COUNT(DISTINCT Attendance.AttendanceDate) AS TotalAttendanceDays
FROM Employee
LEFT JOIN Attendance ON Employee.EmployeeID = Attendance.EmployeeID
GROUP BY Employee.EmployeeID, Employee.FirstName, Employee.LastName;
PRACTISE 7
-- Create ORDERS table
CREATE TABLE ORDERS (
order_id INT PRIMARY KEY,
customer_name VARCHAR(255),
order_date DATE,
total_amount DECIMAL(10, 2)
);

-- Create BANK table


CREATE TABLE BANK (
bank_id INT PRIMARY KEY,
bank_name VARCHAR(255),
account_number VARCHAR(20),
balance DECIMAL(12, 2)
);

-- Create TRANSACTIONS table


CREATE TABLE TRANSACTIONS (
transaction_id INT PRIMARY KEY,
order_id INT,
bank_id INT,
transaction_date DATE,
amount DECIMAL(10, 2),
FOREIGN KEY (order_id) REFERENCES ORDERS(order_id),
FOREIGN KEY (bank_id) REFERENCES BANK(bank_id)
);

-- Insert sample data into ORDERS table


INSERT INTO ORDERS (order_id, customer_name, order_date, total_amount)
VALUES
(1, 'John Doe', '2023-01-01', 100.00),
(2, 'Jane Smith', '2023-02-15', 150.50),
(3, 'Bob Johnson', '2023-03-10', 200.75);

-- Insert sample data into BANK table


INSERT INTO BANK (bank_id, bank_name, account_number, balance)
VALUES
(1, 'ABC Bank', '1234567890', 5000.00),
(2, 'XYZ Bank', '9876543210', 7500.50),
(3, 'PQR Bank', '5555666677778888', 10000.25);

-- Insert sample data into TRANSACTIONS table


INSERT INTO TRANSACTIONS (transaction_id, order_id, bank_id, transaction_date, amount)
VALUES
(101, 1, 1, '2023-01-02', 100.00),
(102, 2, 2, '2023-02-16', 150.50),
(103, 3, 3, '2023-03-11', 200.75);
Questions:-

1.Retrieve all orders with customer names and corresponding transaction amounts.

2.List all transactions with transaction details, including customer names and bank names.

3.Find the total amount spent by each customer.

4.Retrieve the details of orders that have transactions with amounts greater than $150.

5.List the banks with their total transaction amounts, ordered from the highest total amount to the
lowest.
1. Retrieve all orders with customer names and corresponding transaction amounts.
SELECT o.order_id, o.customer_name, t.amount
FROM ORDERS o
JOIN TRANSACTIONS t ON o.order_id = t.order_id;

2. List all transactions with transaction details, including customer names and bank names.

SELECT t.transaction_id, t.transaction_date, o.customer_name, b.bank_name, t.amount


FROM TRANSACTIONS t
JOIN ORDERS o ON t.order_id = o.order_id
JOIN BANK b ON t.bank_id = b.bank_id;

3. Find the total amount spent by each customer.

SELECT o.customer_name, SUM(t.amount) AS total_amount_spent


FROM ORDERS o
JOIN TRANSACTIONS t ON o.order_id = t.order_id
GROUP BY o.customer_name;

4. Retrieve the details of orders that have transactions with amounts greater than $150.

SELECT o.order_id, o.customer_name, t.transaction_id, t.amount


FROM ORDERS o
JOIN TRANSACTIONS t ON o.order_id = t.order_id
WHERE t.amount > 150;

5. List the banks with their total transaction amounts, ordered from the highest total amount
to the lowest.

SELECT b.bank_id, b.bank_name, SUM(t.amount) AS total_transaction_amount


FROM BANK b
JOIN TRANSACTIONS t ON b.bank_id = t.bank_id
GROUP BY b.bank_id, b.bank_name
ORDER BY total_transaction_amount DESC;
PRACTISE 8
-- Create Employees table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DepartmentID INT,
Salary DECIMAL(10, 2)
);

-- Insert sample data into Employees table


INSERT INTO Employees VALUES
(1, 'John', 'Doe', 1, 50000),
(2, 'Jane', 'Smith', 2, 60000),
(3, 'Bob', 'Johnson', 1, 55000),
(4, 'Alice', 'Williams', 3, 70000),
(5, 'Charlie', 'Brown', 2, 65000);

-- Create Departments table


CREATE TABLE Departments (
DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(50),
Location VARCHAR(50),
ManagerID INT,
Budget DECIMAL(12, 2)
);

-- Insert sample data into Departments table


INSERT INTO Departments VALUES
(1, 'IT', 'Building A', 3, 1000000),
(2, 'HR', 'Building B', 2, 800000),
(3, 'Finance', 'Building C', 4, 1200000),
(4, 'Marketing', 'Building D', 5, 900000),
(5, 'Operations', 'Building E', 1, 1100000);
1. List all employees with their department names.

2. Retrieve the total budget for each department.

3. Find the employees who earn more than the average salary in their department.

4. Display the names of managers along with their department names.

5. Show the departments with no employees.

6.Employees with their department names:

7.Total budget for each department: Retrieve the total budget for each department.

8.Employees with salaries above the average: Find the employees who earn more than the average
salary in their department.

9.Display the names of managers along with their department names.

10.Show the departments with no employees


1. List all employees with their department names.

SELECT E.EmployeeID, E.FirstName, E.LastName, D.DepartmentName


FROM Employees E
JOIN Departments D ON E.DepartmentID = D.DepartmentID;

2. Retrieve the total budget for each department.

SELECT D.DepartmentID, D.DepartmentName, SUM(D.Budget) AS TotalBudget


FROM Departments D
JOIN Employees E ON D.DepartmentID = E.DepartmentID
GROUP BY D.DepartmentID, D.DepartmentName;

3. Find the employees who earn more than the average salary in their department.

SELECT E.EmployeeID, E.FirstName, E.LastName, E.Salary, D.DepartmentName


FROM Employees E
JOIN Departments D ON E.DepartmentID = D.DepartmentID
WHERE E.Salary > (SELECT AVG(Salary) FROM Employees WHERE DepartmentID =
E.DepartmentID);

4. Display the names of managers along with their department names.

SELECT M.FirstName AS ManagerFirstName, M.LastName AS ManagerLastName,


D.DepartmentName
FROM Employees E
JOIN Employees M ON E.ManagerID = M.EmployeeID
JOIN Departments D ON E.DepartmentID = D.DepartmentID;

5. Show the departments with no employees.

SELECT D.DepartmentID, D.DepartmentName


FROM Departments D
LEFT JOIN Employees E ON D.DepartmentID = E.DepartmentID
WHERE E.EmployeeID IS NULL;

6.Employees with their department names:

SELECT E.EmployeeID, E.FirstName, E.LastName, D.DepartmentName


FROM Employees E
JOIN Departments D ON E.DepartmentID = D.DepartmentID;
7.Total budget for each department: Retrieve the total budget for each department.

SELECT D.DepartmentID, D.DepartmentName, SUM(D.Budget) AS TotalBudget


FROM Departments D
JOIN Employees E ON D.DepartmentID = E.DepartmentID
GROUP BY D.DepartmentID, D.DepartmentName;

8.Employees with salaries above the average: Find the employees who earn more than the
average salary in their department.

SELECT E.EmployeeID, E.FirstName, E.LastName, E.Salary, D.DepartmentName


FROM Employees E
JOIN Departments D ON E.DepartmentID = D.DepartmentID
WHERE E.Salary > (SELECT AVG(Salary) FROM Employees WHERE DepartmentID = E.DepartmentID);

9.Display the names of managers along with their department names.

SELECT M.FirstName AS ManagerFirstName, M.LastName AS ManagerLastName,


D.DepartmentName
FROM Employees E
JOIN Employees M ON E.ManagerID = M.EmployeeID
JOIN Departments D ON E.DepartmentID = D.DepartmentID;

10.Show the departments with no employees.

SELECT D.DepartmentID, D.DepartmentName


FROM Departments D
LEFT JOIN Employees E ON D.DepartmentID = E.DepartmentID
WHERE E.EmployeeID IS NULL;
PRACTISE 9
-- Create RAILWAY table
CREATE TABLE RAILWAY (
TrainID INT PRIMARY KEY,
TrainName VARCHAR(255) NOT NULL,
DepartureStation VARCHAR(255) NOT NULL,
ArrivalStation VARCHAR(255) NOT NULL,
DepartureTime DATETIME NOT NULL
);

-- Insert sample data into RAILWAY table


INSERT INTO RAILWAY (TrainID, TrainName, DepartureStation, ArrivalStation, DepartureTime)
VALUES
(1, 'Express 101', 'StationA', 'StationB', '2023-01-01 08:00:00'),
(2, 'Local 202', 'StationC', 'StationD', '2023-01-01 10:30:00'),
(3, 'Superfast 303', 'StationE', 'StationF', '2023-01-01 15:45:00');

-- Create BOOKING table


CREATE TABLE BOOKING (
BookingID INT PRIMARY KEY,
TrainID INT,
PassengerName VARCHAR(255) NOT NULL,
SeatNumber INT NOT NULL,
BookingDate DATETIME NOT NULL,
FOREIGN KEY (TrainID) REFERENCES RAILWAY(TrainID)
);

-- Insert sample data into BOOKING table


INSERT INTO BOOKING (BookingID, TrainID, PassengerName, SeatNumber, BookingDate)
VALUES
(101, 1, 'John Doe', 12, '2023-01-02 09:15:00'),
(102, 2, 'Jane Smith', 5, '2023-01-03 11:30:00'),
(103, 3, 'Bob Johnson', 8, '2023-01-04 16:00:00');

Questions:-

1. List all the trains and their departure stations.


2. Find the total number of bookings made for each train.
3. Retrieve the details of passengers who booked a seat for a train departing after 10:00 AM.
4. List all trains along with the count of bookings made for each. Include trains with zero
bookings.
5. Find the train with the highest number of bookings.
6. List the trains that have no bookings.
7. Find the average number of seats booked per train.
8. Retrieve the train name, departure, and arrival stations for bookings made by a specific
passenger (e.g., 'John Doe').
9. List the passengers who booked a seat on a train but did not provide their names (NULL
values).
10. Find the trains with bookings made on a specific date (e.g., '2023-01-02').
1.List all the trains and their departure stations.

SELECT TrainName, DepartureStation


FROM RAILWAY;

2.Find the total number of bookings made for each train.

SELECT r.TrainName, COUNT(b.BookingID) AS TotalBookings


FROM RAILWAY r
LEFT JOIN BOOKING b ON r.TrainID = b.TrainID
GROUP BY r.TrainName;

3.Retrieve the details of passengers who booked a seat for a train departing after 10:00 AM.

SELECT b.PassengerName, b.SeatNumber, r.TrainName, r.DepartureTime


FROM BOOKING b
JOIN RAILWAY r ON b.TrainID = r.TrainID
WHERE r.DepartureTime > '10:00:00';

4.List all trains along with the count of bookings made for each. Include trains with zero
bookings.

SELECT r.TrainName, COUNT(b.BookingID) AS TotalBookings


FROM RAILWAY r
LEFT JOIN BOOKING b ON r.TrainID = b.TrainID
GROUP BY r.TrainName;

5.find the train with the highest number of bookings.

SELECT r.TrainName, COUNT(b.BookingID) AS TotalBookings


FROM RAILWAY r
LEFT JOIN BOOKING b ON r.TrainID = b.TrainID
GROUP BY r.TrainName
ORDER BY TotalBookings DESC
LIMIT 1;

6.List the trains that have no bookings.


SELECT r.TrainName
FROM RAILWAY r
LEFT JOIN BOOKING b ON r.TrainID = b.TrainID
WHERE b.BookingID IS NULL;
7.Find the average number of seats booked per train.

SELECT AVG(SeatNumber) AS AverageSeatsBooked


FROM BOOKING;

8.Retrieve the train name, departure, and arrival stations for bookings made by a specific
passenger (e.g., 'John Doe').

SELECT r.TrainName, r.DepartureStation, r.ArrivalStation


FROM RAILWAY r
JOIN BOOKING b ON r.TrainID = b.TrainID
WHERE b.PassengerName = 'John Doe';

9.List the passengers who booked a seat on a train but did not provide their names (NULL
values).

SELECT PassengerName, TrainName


FROM BOOKING b
JOIN RAILWAY r ON b.TrainID = r.TrainID
WHERE PassengerName IS NULL;

10.Find the trains with bookings made on a specific date (e.g., '2023-01-02').

SELECT DISTINCT r.TrainName


FROM RAILWAY r
JOIN BOOKING b ON r.TrainID = b.TrainID
WHERE DATE(b.BookingDate) = '2023-01-02';

You might also like