Scalar subqueries in PostgreSQL - Time & Space Complexity
When using scalar subqueries in SQL, it's important to understand how the query's running time changes as the data grows.
We want to know how many times the subquery runs and how that affects the total work done.
Analyze the time complexity of the following SQL query using a scalar subquery.
SELECT e.employee_id, e.name,
(SELECT d.department_name
FROM departments d
WHERE d.department_id = e.department_id) AS dept_name
FROM employees e;
This query lists employees and uses a scalar subquery to find each employee's department name.
Look for repeated actions in the query.
- Primary operation: The scalar subquery runs once for each employee row.
- How many times: Equal to the number of employees (n).
As the number of employees grows, the subquery runs more times, increasing total work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 subquery runs |
| 100 | About 100 subquery runs |
| 1000 | About 1000 subquery runs |
Pattern observation: The total work grows roughly in direct proportion to the number of employees.
Time Complexity: O(n)
This means the query's work grows linearly with the number of employees.
[X] Wrong: "The scalar subquery runs just once, so it doesn't affect performance much."
[OK] Correct: The subquery runs once for every employee row, so its cost adds up as the data grows.
Understanding how scalar subqueries scale helps you write efficient queries and explain your reasoning clearly in interviews.
"What if we replaced the scalar subquery with a JOIN? How would that change the time complexity?"
Practice
Solution
Step 1: Understand scalar subquery definition
A scalar subquery returns exactly one value, not multiple rows or columns.Step 2: Compare options with definition
Only A single value used inside another query describes a single value used inside another query, matching the scalar subquery concept.Final Answer:
A single value used inside another query -> Option AQuick Check:
Scalar subquery = single value [OK]
- Thinking scalar subqueries return multiple rows
- Confusing scalar subqueries with table names
- Assuming scalar subqueries return lists
Solution
Step 1: Identify correct scalar subquery syntax
The scalar subquery must be enclosed in parentheses and return a single value, used inside the main SELECT.Step 2: Check each option
SELECT (SELECT MAX(price) FROM products) AS max_price; correctly uses (SELECT MAX(price) FROM products) as a scalar subquery. Options A, B, and D have syntax errors or misuse subqueries.Final Answer:
SELECT (SELECT MAX(price) FROM products) AS max_price; -> Option AQuick Check:
Scalar subquery syntax = SELECT (SELECT MAX(price) FROM products) AS max_price; [OK]
- Omitting parentheses around subquery
- Using incomplete or invalid subquery syntax
- Confusing subqueries with JOINs
products(id, name, price)and
sales(product_id, quantity)What will this query return?
SELECT name, (SELECT SUM(quantity) FROM sales WHERE product_id = products.id) AS total_sold FROM products;
Solution
Step 1: Understand the subquery role
The subquery sums quantity from sales where product_id matches the current product's id, returning total sold per product.Step 2: Analyze the main query output
The main query selects product name and the scalar subquery result as total_sold for each product row.Final Answer:
Each product's name with total quantity sold -> Option DQuick Check:
Scalar subquery sums sales per product = Each product's name with total quantity sold [OK]
- Thinking subquery sums all sales once
- Ignoring WHERE clause linking tables
- Assuming syntax error without checking carefully
SELECT name, (SELECT price FROM products) AS product_price FROM products;
Solution
Step 1: Check subquery result cardinality
The subquery SELECT price FROM products returns multiple prices (rows), not a single value.Step 2: Understand scalar subquery requirement
Scalar subqueries must return exactly one value; multiple rows cause an error.Final Answer:
Subquery returns multiple rows causing error -> Option CQuick Check:
Scalar subquery must return one value [OK]
- Ignoring multiple rows returned by subquery
- Assuming alias fixes multiple rows error
- Confusing syntax error with runtime error
Solution
Step 1: Understand the goal
We want each product's price minus the average price of all products.Step 2: Analyze each option
SELECT name, price - (SELECT AVG(price) FROM products) AS price_diff FROM products; correctly uses a scalar subquery to get AVG(price) once and subtracts it from each product's price. SELECT name, price - AVG(price) FROM products; lacks GROUP BY and will error. SELECT name, price - (SELECT price FROM products) AS price_diff FROM products; returns multiple prices, causing error. SELECT name, price - (SELECT SUM(price) FROM products) AS price_diff FROM products; subtracts sum, not average, which is incorrect.Final Answer:
SELECT name, price - (SELECT AVG(price) FROM products) AS price_diff FROM products; -> Option BQuick Check:
Scalar subquery for AVG(price) = SELECT name, price - (SELECT AVG(price) FROM products) AS price_diff FROM products; [OK]
- Using aggregate without GROUP BY causing error
- Subquery returning multiple rows instead of one
- Confusing SUM with AVG in calculation
Ready to prove it?
Pass the test and this pattern moves unknown
