You are on page 1of 29

1) To retrieve the information about students majoring in Computer Science and enrolled in

courses taught by Professor Smith using relational algebra, you can use the following
expression:

Copy code

π_{student_name} (σ_{major='Computer Science' ∧ professor_name='Professor Smith'} (Students


⨝_{student_id=student_id} (Enrollments ⨝_{course_id=course_id} (Courses
⨝_{professor_id=professor_id} (Professors)))))

Let's break down the expression:

Join Professors with Courses: (Professors ⨝_{professor_id=professor_id} Courses)

This combines the Professors and Courses tables based on the common attribute professor_id.

Join the result with Enrollments: ((Professors ⨝_{professor_id=professor_id} Courses)


⨝_{course_id=course_id} Enrollments)

This further combines the result from step 1 with the Enrollments table based on the common
attribute course_id.

Join the result with Students: (((Professors ⨝_{professor_id=professor_id} Courses)


⨝_{course_id=course_id} Enrollments) ⨝_{student_id=student_id} Students)

This combines the result from step 2 with the Students table based on the common attribute
student_id.

Select relevant rows: σ_{major='Computer Science' ∧ professor_name='Professor Smith'}


(((Professors ⨝_{professor_id=professor_id} Courses) ⨝_{course_id=course_id} Enrollments)
⨝_{student_id=student_id} Students)

This filters the rows based on the condition that the major is 'Computer Science' and the
professor_name is 'Professor Smith'.

Project student names: π_{student_name} (σ_{major='Computer Science' ∧


professor_name='Professor Smith'} (((Professors ⨝_{professor_id=professor_id} Courses)
⨝_{course_id=course_id} Enrollments) ⨝_{student_id=student_id} Students))

Finally, project the student names from the filtered result.


This expression ensures that you get the names of students who are majoring in Computer Science
and are enrolled in courses taught by Professor Smith.

2) To retrieve the names of employees who are assigned to projects in the "Software Development"
department using relational algebra, you can use the following expression:

arduino

Copy code

π_{employee_name} (σ_{department_name='Software Development'} (Employees


⨝_{employee_id=employee_id} (Assignments ⨝_{project_id=project_id} Projects
⨝_{department_id=department_id} Departments)))

Let's break down the expression:

Join Departments with Projects: (Departments ⨝_{department_id=department_id} Projects)

This combines the Departments and Projects tables based on the common attribute department_id.

Join the result with Employees: ((Departments ⨝_{department_id=department_id} Projects)


⨝_{project_id=project_id} Assignments ⨝_{employee_id=employee_id} Employees)

This further combines the result from step 1 with the Assignments and Employees tables based on
the common attributes project_id and employee_id.

Select relevant rows: σ_{department_name='Software Development'} ((Departments


⨝_{department_id=department_id} Projects) ⨝_{project_id=project_id} Assignments
⨝_{employee_id=employee_id} Employees)

This filters the rows based on the condition that the department_name is 'Software Development'.

Project employee names: π_{employee_name} (σ_{department_name='Software Development'}


((Departments ⨝_{department_id=department_id} Projects) ⨝_{project_id=project_id}
Assignments ⨝_{employee_id=employee_id} Employees))

Finally, project the employee names from the filtered result.

This expression ensures that you get the names of employees who are assigned to projects in the
"Software Development" department.
3) Sure, let's design a set of normalized tables for the online bookstore database. We'll start with an
initial set of tables and then go through the normalization steps:

Authors Table:

AuthorID (Primary Key)

AuthorName

Biography

Books Table:

ISBN (Primary Key)

Title

Genre

Price

AuthorID (Foreign Key referencing Authors table)

Customers Table:

CustomerID (Primary Key)

Name

Email

ShippingAddress

Orders Table:

OrderID (Primary Key)

CustomerID (Foreign Key referencing Customers table)

OrderDate

TotalPrice

OrderDetails Table:

OrderDetailID (Primary Key)

OrderID (Foreign Key referencing Orders table)


ISBN (Foreign Key referencing Books table)

Quantity

Subtotal (calculated as Quantity * Book Price)

Now, let's go through the normalization steps:

First Normal Form (1NF):

All tables have atomic values in each column.

No repeating groups.

Second Normal Form (2NF):

All tables are already in 1NF.

No partial dependencies.
In the Orders table, we have the composite primary key {OrderID, ISBN}, and both fields are
necessary to uniquely identify a record.

Third Normal Form (3NF):

All tables are already in 2NF.

No transitive dependencies.

Remove transitive dependency by creating a new table, AuthorGenres:

AuthorGenres Table:

AuthorID (Primary Key)

Genre

Remove Genre from the Books table and link it to the AuthorGenres table through AuthorID.

The modified Books table becomes:


Books Table:

ISBN (Primary Key)

Title

Price

AuthorID (Foreign Key referencing Authors table)

Now, you can join the Books and AuthorGenres tables based on the AuthorID to retrieve the genre
information for each book. This ensures that there are no transitive dependencies, and the database
is in 3NF.

4) Certainly! Let's design a set of normalized tables for the student, courses, instructors,
departments, and enrollments in a university database. We'll follow the normalization steps to
ensure the database is up to at least third normal form (3NF):

Students Table:

StudentID (Primary Key)

FirstName

LastName

Email

Address

DepartmentID (Foreign Key referencing Departments table)

Departments Table:

DepartmentID (Primary Key)

DepartmentName

Instructors Table:

InstructorID (Primary Key)

FirstName

LastName
Email

DepartmentID (Foreign Key referencing Departments table)

Courses Table:

CourseID (Primary Key)

CourseName

DepartmentID (Foreign Key referencing Departments table)

Enrollments Table:

EnrollmentID (Primary Key)

StudentID (Foreign Key referencing Students table)

CourseID (Foreign Key referencing Courses table)

InstructorID (Foreign Key referencing Instructors table)

EnrollmentDate

Grade

Now, let's go through the normalization steps:

First Normal Form (1NF):

All tables have atomic values in each column.

No repeating groups.

Second Normal Form (2NF):

All tables are already in 1NF.

No partial dependencies.

In the Enrollments table, we have the composite primary key {StudentID, CourseID}, and both fields
are necessary to uniquely identify a record.

Third Normal Form (3NF):

All tables are already in 2NF.


No transitive dependencies.

Remove transitive dependencies by creating a new table, InstructorDepartments:

InstructorDepartments Table:

InstructorID (Primary Key)

DepartmentID (Foreign Key referencing Departments table)

Remove DepartmentID from the Instructors table and link it to the InstructorDepartments table
through InstructorID.

The modified Instructors table becomes:

Instructors Table:

InstructorID (Primary Key)

FirstName

LastName

Email

Now, you can join the Instructors and InstructorDepartments tables based on the InstructorID to
retrieve the department information for each instructor. This ensures that there are no transitive
dependencies, and the database is in 3NF.

5) Certainly! Below are the DDL statements for creating the database schema for student enrollment,
courses, professors, and departments. I'll use MySQL syntax for illustration:

sql

Copy code

-- Create Departments Table

CREATE TABLE Departments (


DepartmentID INT PRIMARY KEY,

DepartmentName VARCHAR(255) NOT NULL

);

-- Create Professors Table

CREATE TABLE Professors (

ProfessorID INT PRIMARY KEY,

FirstName VARCHAR(255) NOT NULL,

LastName VARCHAR(255) NOT NULL,

Email VARCHAR(255) UNIQUE NOT NULL,

DepartmentID INT,

FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)

);

-- Create Courses Table

CREATE TABLE Courses (

CourseID INT PRIMARY KEY,

CourseName VARCHAR(255) NOT NULL,

DepartmentID INT,

ProfessorID INT,

FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID),

FOREIGN KEY (ProfessorID) REFERENCES Professors(ProfessorID)

);

-- Create Students Table

CREATE TABLE Students (

StudentID INT PRIMARY KEY,

FirstName VARCHAR(255) NOT NULL,

LastName VARCHAR(255) NOT NULL,

Email VARCHAR(255) UNIQUE NOT NULL

);
-- Create Enrollments Table

CREATE TABLE Enrollments (

EnrollmentID INT PRIMARY KEY,

StudentID INT,

CourseID INT,

FOREIGN KEY (StudentID) REFERENCES Students(StudentID),

FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)

);

In this schema:

The Departments table stores information about university departments.

The Professors table stores information about professors, including their department.
The Courses table stores information about courses, including the department offering the course
and the professor teaching it.

The Students table stores information about students.

The Enrollments table represents the many-to-many relationship between students and courses.
Each record in this table signifies a student enrolled in a specific course.

Please note that this is a basic schema, and you might need to adjust the data types, constraints, and
additional fields based on specific requirements or additional information needed in your
application.

6) Certainly! Below are DDL statements to create a simple database schema for managing inventory,
orders, customers, and suppliers. I'll use MySQL syntax for illustration:

sql

Copy code

-- Create Suppliers Table

CREATE TABLE Suppliers (

SupplierID INT PRIMARY KEY,

SupplierName VARCHAR(255) NOT NULL,

ContactPerson VARCHAR(255),
PhoneNumber VARCHAR(20),

Email VARCHAR(255) UNIQUE

);

-- Create Products Table

CREATE TABLE Products (

ProductID INT PRIMARY KEY,

ProductName VARCHAR(255) NOT NULL,

StockQuantity INT NOT NULL,

Price DECIMAL(10, 2) NOT NULL

);

-- Create ProductSuppliers Table (Associative table for many-to-many relationship)

CREATE TABLE ProductSuppliers (

ProductID INT,

SupplierID INT,

PRIMARY KEY (ProductID, SupplierID),

FOREIGN KEY (ProductID) REFERENCES Products(ProductID),

FOREIGN KEY (SupplierID) REFERENCES Suppliers(SupplierID)

);

-- Create Customers Table

CREATE TABLE Customers (

CustomerID INT PRIMARY KEY,

FirstName VARCHAR(255) NOT NULL,

LastName VARCHAR(255) NOT NULL,

Email VARCHAR(255) UNIQUE NOT NULL,

PhoneNumber VARCHAR(20)

);

-- Create Orders Table


CREATE TABLE Orders (

OrderID INT PRIMARY KEY,

CustomerID INT,

OrderDate DATE NOT NULL,

TotalAmount DECIMAL(10, 2) NOT NULL,

FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)

);

-- Create OrderDetails Table

CREATE TABLE OrderDetails (

OrderDetailID INT PRIMARY KEY,

OrderID INT,

ProductID INT,

Quantity INT NOT NULL,

Subtotal DECIMAL(10, 2) NOT NULL,

FOREIGN KEY (OrderID) REFERENCES Orders(OrderID),

FOREIGN KEY (ProductID) REFERENCES Products(ProductID)

);

In this schema:

The Suppliers table stores information about suppliers.

The Products table stores information about products in the inventory.

The ProductSuppliers table represents the many-to-many relationship between products and
suppliers.

The Customers table stores information about customers.

The Orders table stores information about customer orders.

The OrderDetails table represents the many-to-many relationship between orders and products.

This schema allows for efficient tracking of inventory, supplier relationships, customer orders, and
the details of each order. Adjustments may be needed based on specific business requirements and
additional details you might want to include in your application.
7) Certainly! Below are SQL queries for each of the tasks you mentioned:

Insert a new customer record into the database:

sql

Copy code

INSERT INTO Customer (customer_name, email, shipping_address)

VALUES ('John Doe', 'john.doe@example.com', '123 Main Street, City');

This query adds a new customer to the Customer table.

Update the price of a product with a specific product ID:

sql

Copy code

UPDATE Products

SET price = 29.99

WHERE product_id = 123;

This query updates the price of a product with the specified product_id in the Products table.

Retrieve the total number of orders placed by each customer:

sql

Copy code

SELECT Customer.customer_id, customer_name, COUNT(Orders.order_id) AS total_orders

FROM Customer

LEFT JOIN Orders ON Customer.customer_id = Orders.customer_id

GROUP BY Customer.customer_id, customer_name;

This query retrieves the total number of orders placed by each customer by joining the Customer and
Orders tables and using the COUNT aggregate function.

Delete a product record with a specific product ID:

sql

Copy code

DELETE FROM Products


WHERE product_id = 456;

This query deletes a product record with the specified product_id from the Products table. Please be
cautious while using the DELETE statement as it permanently removes data.

Make sure to replace the sample data and column names with your actual database schema and
data.

8) Calculate the total number of appointments made:

SELECT COUNT(*) AS TotalAppointments

FROM Appointments;

Find the average experience of doctors by specialization:

SELECT Specialization, AVG(Experience) AS AvgExperience

FROM Doctors

GROUP BY Specialization;

Identify the doctor with the most appointments:

SELECT d.DoctorName, COUNT(*) AS TotalAppointments

FROM Doctors d

JOIN Appointments a ON d.DoctorID = a.DoctorID

GROUP BY d.DoctorID, d.DoctorName

ORDER BY TotalAppointments DESC

LIMIT 1;Calculate the total number of appointments scheduled for each day:

SELECT AppointmentDate, COUNT(*) AS TotalAppointments

FROM Appointments

GROUP BY AppointmentDate;
9) Retrieve the names of all products that are currently out of stock.

sql

Copy code

SELECT name

FROM Products

WHERE stock_quantity = 0;

Find the names of all products that have been ordered at least once.

sql

Copy code

SELECT DISTINCT p.name

FROM Products p

JOIN Order_Details od ON p.product_id = od.product_id;

List the names of products that have never been ordered.

sql

Copy code

SELECT name

FROM Products

WHERE product_id NOT IN (SELECT DISTINCT product_id FROM Order_Details);

Retrieve the names of products that have been ordered by customers with a specific customer ID.

sql

Copy code

SELECT DISTINCT p.name

FROM Products p

JOIN Order_Details od ON p.product_id = od.product_id

JOIN Orders o ON od.order_id = o.order_id

WHERE o.customer_id = [specific_customer_id];

Replace [specific_customer_id] with the actual customer ID you want to query for in the fourth task.

10) Retrieve the names of students who have scored higher than the average grade in the subject
'Mathematics':
sql

Copy code

SELECT s.Name

FROM Students s

INNER JOIN Grades g ON s.StudentID = g.StudentID

WHERE g.Subject = 'Mathematics'

AND g.Grade > (SELECT AVG(Grade) FROM Grades WHERE Subject = 'Mathematics');

Retrieve the names of students who are older than the average age of all students:

sql

Copy code

SELECT Name

FROM Students

WHERE Age > (SELECT AVG(Age) FROM Students);

Retrieve the subjects in which the highest grade was achieved:

sql

Copy code

SELECT Subject

FROM Grades

GROUP BY Subject

HAVING Grade = MAX(Grade);

Retrieve the subjects in which at least one student has scored higher than the average grade:

sql

Copy code

SELECT DISTINCT Subject

FROM Grades

WHERE Grade > (SELECT AVG(Grade) FROM Grades);

These queries should help you accomplish the specified tasks with your database schema.

11) Here are the SQL queries for each of the tasks:
Calculate the total number of orders placed:

sql

Copy code

SELECT COUNT(*) AS total_orders

FROM Orders;

Find the total revenue generated from all orders:

sql

Copy code

SELECT SUM(p.price * od.quantity) AS total_revenue

FROM Order_Details od

JOIN Products p ON od.product_id = p.product_id;

Retrieve the average price of products:

sql

Copy code

SELECT AVG(price) AS average_price

FROM Products;

List the maximum and minimum prices of products:

sql

Copy code

SELECT MAX(price) AS max_price, MIN(price) AS min_price

FROM Products;

These queries should provide the desired information based on the provided database schema.

12) Retrieve the names of employees who are earning more than the average salary of all employees
in their respective departments:

sql

Copy code

SELECT e.Name

FROM Employees e

INNER JOIN (
SELECT DepartmentID, AVG(Salary) AS AvgSalary

FROM Employees

GROUP BY DepartmentID

) AS dept_avg ON e.DepartmentID = dept_avg.DepartmentID

WHERE e.Salary > dept_avg.AvgSalary;

Retrieve the names of employees who are earning more than the highest salary in their respective
departments:

sql

Copy code

SELECT e.Name

FROM Employees e

INNER JOIN (

SELECT DepartmentID, MAX(Salary) AS MaxSalary

FROM Employees

GROUP BY DepartmentID

) AS dept_max ON e.DepartmentID = dept_max.DepartmentID

WHERE e.Salary > dept_max.MaxSalary;

Retrieve the names of employees who are earning more than the average salary of employees in the
same department with a higher employee ID:

sql

Copy code

SELECT e1.Name

FROM Employees e1

INNER JOIN Employees e2 ON e1.DepartmentID = e2.DepartmentID AND e1.EmployeeID <


e2.EmployeeID

INNER JOIN (

SELECT DepartmentID, AVG(Salary) AS AvgSalary

FROM Employees

GROUP BY DepartmentID

) AS dept_avg ON e1.DepartmentID = dept_avg.DepartmentID

WHERE e1.Salary > dept_avg.AvgSalary;


Retrieve the names of employees who have the same salary as the employee with the highest salary
in their department:

sql

Copy code

SELECT e1.Name

FROM Employees e1

INNER JOIN (

SELECT DepartmentID, MAX(Salary) AS MaxSalary

FROM Employees

GROUP BY DepartmentID

) AS dept_max ON e1.DepartmentID = dept_max.DepartmentID

WHERE e1.Salary = dept_max.MaxSalary;

13) Retrieve the names of all students majoring in Computer Science:

sql

Copy code

SELECT name

FROM Students

WHERE major = 'Computer Science';

Find the names of all courses offered by the Computer Science department:

sql

Copy code

SELECT name

FROM Courses

WHERE department = 'Computer Science';

List the names of students who are enrolled in at least one course offered by the Computer Science
department:

sql

Copy code

SELECT DISTINCT s.name

FROM Students s
JOIN Enrollments e ON s.student_id = e.student_id

JOIN Courses c ON e.course_id = c.course_id

WHERE c.department = 'Computer Science';

Retrieve the names of all students who are not enrolled in any course:

sql

Copy code

SELECT name

FROM Students

WHERE student_id NOT IN (SELECT DISTINCT student_id FROM Enrollments);

14) Retrieve the names of employees who have the highest salary in each department for the year
2023:

sql

Copy code

SELECT e.Name, d.DepartmentName, s.Salary

FROM Employees e

JOIN Departments d ON e.DepartmentID = d.DepartmentID

JOIN Salaries s ON e.EmployeeID = s.EmployeeID

WHERE s.Year = 2023

AND (s.Salary, e.DepartmentID) IN (

SELECT MAX(Salary), DepartmentID

FROM Salaries

WHERE Year = 2023

GROUP BY DepartmentID

);

Retrieve the department names along with the total salary expenditure for each department in the
year 2023:

sql

Copy code

SELECT d.DepartmentName, SUM(s.Salary) AS TotalSalaryExpenditure

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

JOIN Salaries s ON e.EmployeeID = s.EmployeeID

WHERE s.Year = 2023

GROUP BY d.DepartmentName;

Retrieve the names of employees who have changed departments at least once:

sql

Copy code

SELECT DISTINCT e.Name

FROM Employees e

GROUP BY e.Name

HAVING COUNT(DISTINCT e.DepartmentID) > 1;

Retrieve the names of employees who have earned a salary higher than the average salary of all
employees in the year 2023:

sql

Copy code

SELECT e.Name, s.Salary

FROM Employees e

JOIN Salaries s ON e.EmployeeID = s.EmployeeID

WHERE s.Year = 2023

AND s.Salary > (

SELECT AVG(Salary)

FROM Salaries

WHERE Year = 2023

);

These queries should give you the desired results based on the given schema and requirements.

15) Retrieve the names of customers who have placed orders:

sql

Copy code

SELECT DISTINCT c.name


FROM Customers c

JOIN Orders o ON c.customer_id = o.customer_id;

Find the total number of orders placed by each customer:

sql

Copy code

SELECT c.name, COUNT(o.order_id) AS total_orders

FROM Customers c

JOIN Orders o ON c.customer_id = o.customer_id

GROUP BY c.name;

List the names of customers who have placed more than one order:

sql

Copy code

SELECT c.name

FROM Customers c

JOIN Orders o ON c.customer_id = o.customer_id

GROUP BY c.name

HAVING COUNT(o.order_id) > 1;

Retrieve the names of customers who have placed an order after a specific date (let's assume the
specific date is 'YYYY-MM-DD'):

sql

Copy code

SELECT DISTINCT c.name

FROM Customers c

JOIN Orders o ON c.customer_id = o.customer_id

WHERE o.order_date > 'YYYY-MM-DD';

16)Certainly! Below are SQL queries for each of the tasks you mentioned:

List the names of all products ordered by a specific customer:

sql

Copy code
SELECT DISTINCT Products.name

FROM Customers

JOIN Orders ON Customers.customer_id = Orders.customer_id

JOIN Order_Details ON Orders.order_id = Order_Details.order_id

JOIN Products ON Order_Details.product_id = Products.product_id

WHERE Customers.customer_id = 1; -- Replace 1 with the specific customer_id

This query retrieves the names of all products ordered by a specific customer by joining the relevant
tables.

Retrieve the total number of orders for a specific product:

sql

Copy code

SELECT Products.name, COUNT(Orders.order_id) AS total_orders

FROM Products

LEFT JOIN Order_Details ON Products.product_id = Order_Details.product_id

LEFT JOIN Orders ON Order_Details.order_id = Orders.order_id

WHERE Products.product_id = 101; -- Replace 101 with the specific product_id

GROUP BY Products.name;

This query calculates the total number of orders for a specific product by joining the relevant tables
and using the COUNT aggregate function.

Calculate the total revenue generated from a specific product:

sql

Copy code

SELECT Products.name, SUM(Products.price * Order_Details.quantity) AS total_revenue

FROM Products

JOIN Order_Details ON Products.product_id = Order_Details.product_id

WHERE Products.product_id = 201; -- Replace 201 with the specific product_id

GROUP BY Products.name;

This query calculates the total revenue generated from a specific product by multiplying the price
with the quantity and using the SUM aggregate function.
List the names of customers who have never placed an order:

sql

Copy code

SELECT Customers.name

FROM Customers

LEFT JOIN Orders ON Customers.customer_id = Orders.customer_id

WHERE Orders.customer_id IS NULL;

This query retrieves the names of customers who have never placed an order by using a LEFT JOIN
and checking for NULL values in the Orders table.

Make sure to replace the sample data and column names with your actual database schema and
data.

17) Certainly! Below are SQL queries for each of the tasks you mentioned:

Retrieve the names of customers who have placed orders for products that are priced higher than
the average price of all products:

sql

Copy code

SELECT DISTINCT C.Name

FROM Customers C

JOIN Orders O ON C.CustomerID = O.CustomerID

JOIN Products P ON O.ProductID = P.ProductID

WHERE P.Price > (SELECT AVG(Price) FROM Products);

This query retrieves the names of customers who have placed orders for products priced higher than
the average price of all products.

Retrieve the names of customers who have placed orders for more than one product:

sql

Copy code

SELECT C.Name
FROM Customers C

JOIN Orders O ON C.CustomerID = O.CustomerID

GROUP BY C.CustomerID, C.Name

HAVING COUNT(DISTINCT O.ProductID) > 1;

This query retrieves the names of customers who have placed orders for more than one product by
using the COUNT function and GROUP BY clause.

Retrieve the names of customers who have placed orders for products with a total quantity greater
than the average quantity of all products:

sql

Copy code

SELECT C.Name

FROM Customers C

JOIN Orders O ON C.CustomerID = O.CustomerID

JOIN Products P ON O.ProductID = P.ProductID

GROUP BY C.CustomerID, C.Name

HAVING SUM(O.Quantity) > (SELECT AVG(Quantity) FROM Orders);


This query retrieves the names of customers who have placed orders for products with a total
quantity greater than the average quantity of all products.

Retrieve the names of customers who have placed orders for all available products:

sql

Copy code

SELECT C.Name

FROM Customers C

WHERE NOT EXISTS (

SELECT P.ProductID

FROM Products P

WHERE NOT EXISTS (

SELECT O.ProductID

FROM Orders O

WHERE O.CustomerID = C.CustomerID


AND O.ProductID = P.ProductID

);

This query retrieves the names of customers who have placed orders for all available products by
using the NOT EXISTS clause.

Make sure to replace the sample data and column names with your actual database schema and
data.

18) ertainly! Below are SQL queries for each of the tasks you mentioned:

Retrieve the titles of books along with the names of authors for books that are currently available:

sql

Copy code

SELECT Books.Title, Authors.AuthorName

FROM Books

JOIN BookAuthors ON Books.BookID = BookAuthors.BookID

JOIN Authors ON BookAuthors.AuthorID = Authors.AuthorID

WHERE Books.Availability = 'available';

This query retrieves the titles of books along with the names of authors for books that are currently
available by joining the Books, BookAuthors, and Authors tables.

Retrieve the titles of books along with the names of authors for books with ISBN starting with '978':

sql

Copy code

SELECT Books.Title, Authors.AuthorName

FROM Books

JOIN BookAuthors ON Books.BookID = BookAuthors.BookID

JOIN Authors ON BookAuthors.AuthorID = Authors.AuthorID

WHERE Books.ISBN LIKE '978%';


This query retrieves the titles of books along with the names of authors for books with ISBN starting
with '978' by using the LIKE operator.

Retrieve the titles of books along with the names of authors for books written by authors whose
names start with 'J':

sql

Copy code

SELECT Books.Title, Authors.AuthorName

FROM Books

JOIN BookAuthors ON Books.BookID = BookAuthors.BookID

JOIN Authors ON BookAuthors.AuthorID = Authors.AuthorID

WHERE Authors.AuthorName LIKE 'J%';

This query retrieves the titles of books along with the names of authors for books written by authors
whose names start with 'J' using the LIKE operator.

Retrieve the titles of books along with the names of authors for books published after the year 2010:

sql

Copy code

SELECT Books.Title, Authors.AuthorName

FROM Books

JOIN BookAuthors ON Books.BookID = BookAuthors.BookID

JOIN Authors ON BookAuthors.AuthorID = Authors.AuthorID

WHERE YEAR(Books.PublicationDate) > 2010;

This query retrieves the titles of books along with the names of authors for books published after the
year 2010 by using the YEAR function on the PublicationDate column.

Make sure to replace the sample column names with your actual database schema and data.

19) Certainly! Below are SQL queries for each of the tasks you mentioned:

List the names of all courses taken by a specific student:


sql

Copy code

SELECT Courses.name

FROM Students

JOIN Enrollments ON Students.student_id = Enrollments.student_id

JOIN Courses ON Enrollments.course_id = Courses.course_id

WHERE Students.name = 'John Doe'; -- Replace 'John Doe' with the specific student name

This query retrieves the names of all courses taken by a specific student by joining the Students,
Enrollments, and Courses tables.

Retrieve the total number of courses taken by each student:

sql

Copy code

SELECT Students.name, COUNT(Enrollments.course_id) AS total_courses

FROM Students

LEFT JOIN Enrollments ON Students.student_id = Enrollments.student_id

GROUP BY Students.name;

This query calculates the total number of courses taken by each student by using the COUNT
aggregate function and joining the Students and Enrollments tables.

Calculate the total number of students enrolled in each department:

sql

Copy code

SELECT Courses.department, COUNT(DISTINCT Students.student_id) AS total_students

FROM Courses

LEFT JOIN Enrollments ON Courses.course_id = Enrollments.course_id

LEFT JOIN Students ON Enrollments.student_id = Students.student_id

GROUP BY Courses.department;

This query calculates the total number of students enrolled in each department by using the COUNT
aggregate function and joining the Courses, Enrollments, and Students tables.

Retrieve the names of students who are not enrolled in any course:
sql

Copy code

SELECT Students.name

FROM Students

LEFT JOIN Enrollments ON Students.student_id = Enrollments.student_id

WHERE Enrollments.enrollment_id IS NULL;

This query retrieves the names of students who are not enrolled in any course by using a LEFT JOIN
and checking for NULL values in the Enrollments table.

Make sure to replace the sample data and column names with your actual database schema and
data.

20) Retrieve the names of customers along with the total amount spent by each customer:

SELECT c.CustomerName, SUM(p.Price * o.Quantity) AS TotalAmountSpent

FROM Customers c

JOIN Orders o ON c.CustomerID = o.CustomerID

JOIN Products p ON o.ProductID = p.ProductID

GROUP BY c.CustomerID, c.CustomerName;

Retrieve the product names along with the total quantity sold for each product:

SELECT p.ProductName, SUM(o.Quantity) AS TotalQuantitySold

FROM Products p

JOIN Orders o ON p.ProductID = o.ProductID


GROUP BY p.ProductID, p.ProductName;

Retrieve the product names along with the total amount earned for each product:

SELECT p.ProductName, SUM(p.Price * o.Quantity) AS TotalAmountEarned

FROM Products p

JOIN Orders o ON p.ProductID = o.ProductID

GROUP BY p.ProductID, p.ProductName;

Retrieve the names of customers along with the products they have ordered, ordered in descending
order of order dates:

SELECT c.CustomerName, p.ProductName, o.OrderDate

FROM Customers c

JOIN Orders o ON c.CustomerID = o.CustomerID

JOIN Products p ON o.ProductID = p.ProductID

ORDER BY o.OrderDate DESC;

You might also like