Using Scalar Subqueries in PostgreSQL
📖 Scenario: You are managing a small bookstore database. You want to find the price of each book along with the average price of all books in the store.
🎯 Goal: Build a SQL query that uses a scalar subquery to show each book's title, its price, and the average price of all books.
📋 What You'll Learn
Create a table called
books with columns id (integer), title (text), and price (numeric).Insert exactly three books with these values: (1, 'Book A', 10.00), (2, 'Book B', 15.00), (3, 'Book C', 20.00).
Write a scalar subquery to calculate the average price of all books.
Select the
title, price, and the average price from the scalar subquery in the final query.💡 Why This Matters
🌍 Real World
Scalar subqueries are useful when you want to include a single value calculated from the database inside another query, such as averages, counts, or maximum values.
💼 Career
Understanding scalar subqueries helps you write efficient and readable SQL queries for reports and data analysis tasks in many database-related jobs.
Progress0 / 4 steps