Using Scalar Subquery in SELECT
📖 Scenario: You are managing a small bookstore database. You have two tables: books and sales. The books table stores book details, and the sales table records each sale with the book's ID and quantity sold.You want to create a report that shows each book's title along with the total quantity sold for that book.
🎯 Goal: Build a SQL query that lists each book's title and the total quantity sold using a scalar subquery inside the SELECT clause.
📋 What You'll Learn
Create a
books table with columns book_id (integer) and title (text).Create a
sales table with columns sale_id (integer), book_id (integer), and quantity (integer).Insert the exact data provided for both tables.
Write a SELECT query on
books that uses a scalar subquery in the SELECT clause to find total quantity sold per book.The scalar subquery must use
SUM(quantity) from sales filtered by the current book_id.💡 Why This Matters
🌍 Real World
Scalar subqueries in SELECT help you calculate related data for each row without complex joins, useful in reports and dashboards.
💼 Career
Understanding scalar subqueries is important for database querying roles, data analysis, and backend development where you need to fetch aggregated data efficiently.
Progress0 / 4 steps