Using Multiple CTEs in One SQL Query
📖 Scenario: You work for a small bookstore. You have a database with sales data and book details. You want to find the total sales for each book and then find which books sold more than 50 copies.
🎯 Goal: Build a SQL query using two Common Table Expressions (CTEs). The first CTE calculates total sales per book. The second CTE filters books with sales greater than 50. Finally, select the book title and total sales from the filtered results.
📋 What You'll Learn
Create a CTE named
BookSales that sums sales per book_id from the sales table.Create a second CTE named
TopSellingBooks that selects books from BookSales with total sales greater than 50.Join
TopSellingBooks with the books table to get the book titles.Select the book title and total sales in the final output.
💡 Why This Matters
🌍 Real World
Using multiple CTEs helps break complex queries into smaller parts, making them easier to read and maintain in real business databases.
💼 Career
Many data analyst and database developer jobs require writing queries with multiple CTEs to organize data processing steps clearly.
Progress0 / 4 steps