Library and Online Shop SQL Queries
Library and Online Shop SQL Queries
To efficiently add a new column for storing phone numbers in the Customers table, use the ALTER TABLE statement: ALTER TABLE Customers ADD phone VARCHAR(20); This alters the table schema by adding a new column for phone numbers .
To list courses taught by 'Dr. Johnson', the query would be: SELECT c.course_name FROM Courses c JOIN CourseProfessors cp ON c.course_id = cp.course_id JOIN Professors p ON cp.prof_id = p.prof_id WHERE p.prof_name = 'Dr. Johnson'; This retrieves all course names associated with the professor .
To retrieve hires before a specific date, such as '2021-01-01', use the query: SELECT * FROM Librarians WHERE hire_date < '2021-01-01'; This filters the dataset to show only librarians hired before January 1, 2021 .
To find the names of all members who have never borrowed a book, you would use a LEFT JOIN to locate members without any corresponding borrowings. The SQL query would be: SELECT m.name FROM Members m LEFT JOIN Borrowings b ON m.member_id = b.member_id WHERE b.member_id IS NULL; .
To determine the presence and count of book genres, employ the query: SELECT genre, COUNT(*) FROM Books GROUP BY genre; This groups books by their genre and counts them .
You can determine which product generated the highest revenue by calculating the total revenue for each product and then comparing them. Use the query: SELECT p.product_name, SUM(oi.quantity * p.price) AS revenue FROM OrderItems oi JOIN Products p ON oi.product_id = p.product_id GROUP BY p.product_name ORDER BY revenue DESC LIMIT 1; This gives you the product with the highest total revenue .
To find the most popular course based on enrollment, use the query: SELECT c.course_name FROM Courses c JOIN Enrollments e ON c.course_id = e.course_id GROUP BY c.course_id, c.course_name ORDER BY COUNT(*) DESC LIMIT 1; This ranks courses by student count and retrieves the top one .
To retrieve the average age of Computer Science students, use the SQL query: SELECT AVG(age) FROM Students WHERE dept_id = 'CS'; This calculates the average age of all students in the Computer Science department .
To update book availability information in specific branches, the SQL query would be: UPDATE BookStocks SET available_copies = 1 WHERE book_id = 2 AND branch = 'Central'; This specifically updates the available copies of a book at the Central branch .
To find all customers who have not placed any orders, utilize a LEFT JOIN to identify customers without order records: SELECT c.name FROM Customers c LEFT JOIN Orders o ON c.customer_id = o.customer_id WHERE o.customer_id IS NULL; This ensures a list of customers without any orders .