Why Subqueries Are Needed in PostgreSQL
📖 Scenario: You work at a bookstore that keeps track of sales and books in a PostgreSQL database. You want to find out which books have sold more copies than the average number of copies sold across all books.
🎯 Goal: Build a query using a subquery to find books with sales above the average sales.
📋 What You'll Learn
Create a table called
books with columns book_id (integer) and title (text).Create a table called
sales with columns sale_id (integer), book_id (integer), and copies_sold (integer).Insert given sample data into both tables.
Write a subquery to calculate the average copies sold across all books.
Write a main query that uses the subquery to find books with copies sold greater than the average.
💡 Why This Matters
🌍 Real World
Subqueries help answer complex questions like comparing individual sales to overall averages in business databases.
💼 Career
Knowing subqueries is essential for database analysts and developers to write efficient and powerful SQL queries.
Progress0 / 4 steps