Sub topic 8
Subqueries in the SELECT List
What to expect
This chapter assumes you can write SELECT, WHERE, and ORDER BY clauses, use aggregate functions such as COUNT and AVG, and understand JOIN and NULL. You will learn how to put a subquery in the SELECT list to calculate an extra value for every row in the main query.
A subquery in the SELECT list is a query inside the columns being returned. It must produce one value for each outer row. This form is called a scalar subquery. The database evaluates the inner query in the context of the current row from the outer query.
Suppose each customer can have many orders. You can return the customer name and a count of that customer's orders:
SELECT c.name,
(SELECT COUNT(*)
FROM orders o
WHERE o.customer_id = c.id) AS order_count
FROM customers c;The c.id reference connects the inner query to the current customer. For each customer, the database counts matching rows in orders. COUNT(*) returns 0 when no orders match, so customers without orders still appear.
How the outer row is used
The subquery above is correlated. A correlated subquery is a subquery that refers to a column from the outer query. Conceptually, the database performs these steps:
The diagram describes the logical behavior. A database optimizer may execute the query in a different physical way, such as rewriting it as a join and aggregation.
A scalar subquery must return at most one value for each outer row. Aggregate functions usually satisfy this requirement because they return one result row:
SELECT d.name,
(SELECT AVG(e.salary)
FROM employees e
WHERE e.department_id = d.id) AS average_salary
FROM departments d;If a department has no employees, AVG returns NULL. This is different from COUNT(*), which returns 0. The distinction matters when applications display or compare the result.
| Inner expression | No matching rows |
|---|---|
| `COUNT(*)` | `0` |
| `AVG(salary)` | `NULL` |
| A plain column query | `NULL` if no row, but an error if multiple rows |
Avoiding multiple-row errors
A scalar subquery cannot return two or more rows. This query is unsafe if a customer can have several orders:
SELECT c.name,
(SELECT o.total
FROM orders o
WHERE o.customer_id = c.id) AS order_total
FROM customers c;A customer with multiple orders causes a runtime error in many SQL systems. Use an aggregate when you need one summary value, or restrict the result deliberately:
SELECT c.name,
(SELECT o.total
FROM orders o
WHERE o.customer_id = c.id
ORDER BY o.total DESC
FETCH FIRST 1 ROW ONLY) AS largest_order
FROM customers c;The row-limiting syntax differs between database systems. PostgreSQL and MySQL commonly use LIMIT 1.
When this form is useful
A SELECT-list subquery works well when the calculated value is a single fact that belongs beside each outer row, such as an order count or a latest timestamp. For several calculated columns, large tables, or complex filtering, a grouped join or CTE may be easier to optimize and maintain. Check the query plan when the outer query returns many rows, because a correlated expression may appear to run once per row.
Exercise
What does the correlated subquery in the customer example count, and what value does it return for a customer with no orders?
Show answer
It counts orders whose customer_id matches the current customer's id. It returns 0 because COUNT(*) returns zero when no rows match.