Sub topic 8
Subqueries in the SELECT List
A subquery in the SELECT list produces one extra column, computed separately for each row the outer query returns. This chapter covers how that works, how it differs from a join, and where it fails.
This chapter assumes you can write basic SELECT, WHERE, and ORDER BY clauses and use aggregate functions with GROUP BY. It also assumes you know INNER JOIN and LEFT JOIN, and that you understand NULL and three-valued logic. You should already know what a scalar subquery and a correlated subquery are.
The working model
A SELECT-list subquery is a scalar subquery used as a column expression. It must return exactly one column and at most one row. If it returns no row, the value is NULL. If it returns more than one row, the database raises an error.
Most useful SELECT-list subqueries are correlated. They refer to a column of the outer row, so the result differs from row to row.
SELECT c.name,
(SELECT COUNT(*)
FROM orders o
WHERE o.customer_id = c.id) AS order_count
FROM customers c;Conceptually, the database does the following for each row of customers:
- Read the current customer,
c. - Run the inner query with
c.idfilled in. - Put the single result into the
order_countcolumn.
Optimizers often rewrite this into a join or aggregate instead of running the inner query once per row. Treat the per-row description as the meaning of the query, not as a promise about how it runs.
Zero rows versus NULL
The example above returns 0 for a customer with no orders, because COUNT(*) always returns exactly one row, even over an empty set. Other aggregates behave differently.
SELECT c.name,
(SELECT SUM(o.total)
FROM orders o
WHERE o.customer_id = c.id) AS lifetime_total
FROM customers c;For a customer with no orders, SUM returns NULL, not 0. The subquery still returns one row, and that row contains NULL. If you want 0, wrap the subquery in COALESCE.
SELECT c.name,
COALESCE((SELECT SUM(o.total)
FROM orders o
WHERE o.customer_id = c.id), 0) AS lifetime_total
FROM customers c;A subquery that has no aggregate and matches no rows returns an empty result. In a SELECT list, an empty result is converted to NULL.
| Inner query shape | No matching rows | Several matching rows |
|---|---|---|
| `COUNT(*)` | 0 | One row, the count |
| `SUM`, `AVG`, `MAX`, `MIN` | NULL | One row, the aggregate |
| Plain column, no aggregate | NULL | Error |
Fetching a value from a related row
A common use is pulling one column from a related table, such as a customer's most recent order date.
SELECT c.name,
(SELECT MAX(o.order_date)
FROM orders o
WHERE o.customer_id = c.id) AS last_order_date
FROM customers c
ORDER BY last_order_date DESC;The alias last_order_date can be used in ORDER BY, because ORDER BY is evaluated after the SELECT list. You cannot use it in WHERE in most databases. To filter on it, repeat the expression or wrap the query in a derived table.
Using an aggregate like MAX guarantees one row. Without it, the inner query might return several rows and fail.
-- Fails if a customer has more than one order
SELECT c.name,
(SELECT o.order_date
FROM orders o
WHERE o.customer_id = c.id) AS order_date
FROM customers c;The error message differs by database. PostgreSQL reports that the subquery used as an expression returned more than one row. MySQL reports that the subquery returns more than one row. The problem appears only when the data contains such a customer, so a query can work in testing and fail in production.
Several columns from the same related row
A SELECT-list subquery returns one column. If you need both the date and the total of the latest order, you cannot return them from one subquery. The tempting workaround is two subqueries.
SELECT c.name,
(SELECT o.order_date
FROM orders o
WHERE o.customer_id = c.id
ORDER BY o.order_date DESC
LIMIT 1) AS last_order_date,
(SELECT o.total
FROM orders o
WHERE o.customer_id = c.id
ORDER BY o.order_date DESC
LIMIT 1) AS last_order_total
FROM customers c;This works, but it repeats the same lookup and can give inconsistent pairs if two orders share a date and the sort order is not fully determined. Add a tie-breaker such as o.id DESC to the ORDER BY. Better, use a lateral subquery or a join so that both columns come from one lookup. A later chapter covers lateral subqueries.
LIMIT is the syntax in PostgreSQL, MySQL, and SQLite. SQL Server uses TOP 1, and the standard form is FETCH FIRST 1 ROW ONLY.
Combining SELECT-list subqueries with other expressions
The subquery is an ordinary expression, so you can use it in arithmetic, in CASE, or inside a function.
SELECT e.name,
e.salary,
e.salary - (SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department_id = e.department_id) AS diff_from_dept_avg
FROM employees e;SELECT c.name,
CASE
WHEN (SELECT COUNT(*)
FROM orders o
WHERE o.customer_id = c.id) = 0 THEN 'inactive'
ELSE 'active'
END AS status_label
FROM customers c;The second query is clearer with EXISTS, which can stop at the first matching row.
SELECT c.name,
CASE
WHEN EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
THEN 'active'
ELSE 'inactive'
END AS status_label
FROM customers c;SELECT-list subquery versus join
The same result can often be written as a LEFT JOIN with GROUP BY.
SELECT c.name,
COUNT(o.id) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name;Note COUNT(o.id) rather than COUNT(*). With a LEFT JOIN, a customer with no orders still produces one row, filled with NULLs. COUNT(*) would count that row and report 1. COUNT(o.id) skips NULLs and reports 0.
| Concern | SELECT-list subquery | LEFT JOIN with GROUP BY |
|---|---|---|
| Customers with no orders | Kept automatically | Kept because of the LEFT JOIN |
| Several unrelated aggregates | Each is isolated in its own subquery | Joining two child tables multiplies rows and inflates counts |
| Outer query grouping | No GROUP BY needed on the outer query | Every selected outer column must be grouped |
| Several columns from one related row | Needs one subquery per column | One join supplies all columns |
| Readability for one extra column | Short and local | More syntax |
The multiplication problem is the strongest reason to prefer subqueries. Suppose you want each customer's order count and ticket count.
-- Wrong: counts are inflated
SELECT c.name,
COUNT(o.id) AS order_count,
COUNT(t.id) AS ticket_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
LEFT JOIN tickets t ON t.customer_id = c.id
GROUP BY c.id, c.name;A customer with 3 orders and 4 tickets produces 12 joined rows, so both counts become 12. Two separate subqueries avoid this, because each one counts only its own table.
SELECT c.name,
(SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS order_count,
(SELECT COUNT(*) FROM tickets t WHERE t.customer_id = c.id) AS ticket_count
FROM customers c;Performance and gotchas
Each SELECT-list subquery is a separate piece of work, and a query with five of them may do five separate lookups per outer row. The cost depends on three things.
- Index on the correlation column.
orders.customer_idshould be indexed. Without it, each lookup scans the wholeorderstable, and the total work grows with the product of the two table sizes. - Number of outer rows. The subquery runs for every row the outer query produces, so a query that returns 1 million customers does 1 million lookups, unless the optimizer rewrites it. Apply
WHEREandLIMITon the outer query to reduce that. - Number of subqueries. Several subqueries that scan the same child table with the same condition are better replaced with one derived table that aggregates once.
SELECT c.name,
s.order_count,
s.total_spent
FROM customers c
LEFT JOIN (
SELECT customer_id,
COUNT(*) AS order_count,
SUM(total) AS total_spent
FROM orders
GROUP BY customer_id
) AS s ON s.customer_id = c.id;Here order_count and total_spent are NULL for customers with no orders. Use COALESCE(s.order_count, 0) if you want zeros.
Other behaviours to keep in mind:
- A SELECT-list subquery cannot be referenced by name in the same SELECT list. You cannot write
order_count * 2in a later column using the alias. - Window functions can often replace per-department comparisons such as
salary - AVG(salary) OVER (PARTITION BY department_id), and they are usually clearer. - Check the query plan with
EXPLAIN. In PostgreSQL, aSubPlannode under the outer scan means the subquery is evaluated per row. A join node means the optimizer rewrote it.
Summary of decision criteria
- Use a SELECT-list subquery for a single value looked up from related rows.
- Guard it with an aggregate, a unique key, or
LIMITwith a deterministic ORDER BY so that it never returns more than one row. - Decide deliberately between 0 and NULL for the no-match case.
- Prefer separate subqueries over multiple joins when counting or summing from two or more child tables.
- Prefer a join, derived table, or lateral subquery when you need several columns from the same related row.
Exercise
A query lists each department with the number of employees and the number of open projects, using LEFT JOIN to both employees and projects and GROUP BY on the department. A department with 5 employees and 2 open projects shows 10 for both counts. Why, and how can SELECT-list subqueries fix it?
Show answer
Joining both child tables produces one row per employee-project pair, so a department with 5 employees and 2 projects yields 10 joined rows, and COUNT over either table sees 10. Replace the joins with two correlated subqueries in the SELECT list: (SELECT COUNT() FROM employees e WHERE e.departmentid = d.id) AS employeecount and (SELECT COUNT() FROM projects p WHERE p.departmentid = d.id AND p.status = 'open') AS openproject_count. Each subquery counts only its own table, giving 5 and 2.
Exercise
This query fails for some customers with an error about a subquery returning more than one row. Rewrite it so it returns each customer's most recent order total and is deterministic when two orders share a date. SELECT c.name, (SELECT o.total FROM orders o WHERE o.customerid = c.id) AS lasttotal FROM customers c;
Show answer
Order the inner query and limit it to one row, with a tie-breaker: (SELECT o.total FROM orders o WHERE o.customerid = c.id ORDER BY o.orderdate DESC, o.id DESC LIMIT 1) AS last_total. The tie-breaker on o.id makes the choice repeatable. In SQL Server, use SELECT TOP 1 instead of LIMIT 1. Customers with no orders get NULL.
Exercise
What does (SELECT SUM(total) FROM orders WHERE customer_id = c.id) return for a customer with no orders, and how do you make it return 0?
Show answer
It returns NULL, because SUM over an empty set is NULL. Wrap it in COALESCE: COALESCE((SELECT SUM(total) FROM orders WHERE customer_id = c.id), 0).