Recipe · SQL recipes

Aliases in subqueries

Give the subquery in FROM an alias and use it to refer to its columns from the outer query.

Before continuing: This entry is part of the aliases guide. If you are new to the topic, start with Alias.

Query

Customers with two or more non-cancelled orders
SELECT c.name AS customer,
       r.total_orders,
       ROUND(r.total_amount, 2) AS total_amount
FROM customers AS c
INNER JOIN (
  SELECT customer_id,
         COUNT(*) AS total_orders,
         SUM(total) AS total_amount
  FROM orders
  WHERE status <> 'cancelled'
  GROUP BY customer_id
) AS r
  ON r.customer_id = c.id
WHERE r.total_orders >= 2
ORDER BY total_amount DESC;

The subquery r summarises the orders per customer. The outer query no longer needs to recompute the count and the sum: it uses r.total_orders and r.total_amount like columns of a table.

How aliases work in subqueries

The SQL standard requires an alias for a subquery placed in FROM, but whether it is required in practice varies between engines. Recent PostgreSQL lets you leave out both AS and the subquery's alias, whereas other engines require a name for the derived table. Even where it is optional, an explicit alias shows where the inner result ends and lets you qualify its columns clearly.

Common mix-ups with subquery aliases

Exposing two columns with the same name

If the outer table and the subquery both have a column called id, writing just id can be ambiguous. Qualify the reference: c.id or r.customer_id.

Also avoid SELECT * inside the subquery. Selecting only the columns you need documents what the derived result provides and avoids surprises when the base table changes.

The derived table draws a line between detail and summary

Give the alias a role you can read: order_summary explains what the derived table does better than a single letter when the query has several layers. Its output columns are what the outer query can see. A detail column that is not selected inside cannot be reached from outside by putting the alias in front of its name.

Decide the level of the summary before joining it. If you group by customer, you expect at most one summary row per customer. If you add status to the grouping, you may get several, and joining them to customers changes the size of the result. The alias does not prevent that multiplication. To check, run the subquery on its own and review the keys of its rows before putting it back into FROM.

This separation lets you filter metrics that are already calculated without repeating their expressions. In the small example, Amy has two orders and Liam has one, so the outer filter keeps only Amy. If an extra table holds several addresses per customer, joining it before counting could inflate the count. Summarise the set you want to measure first, then decide which relationships you can add without duplicating the metrics.

Self-contained case to check in SQLite

The inner query returns one row per customer; the outer one filters on a column of that summary.

Data and query · SQLite
WITH orders(customer, amount) AS (
  VALUES ('Amy', 20), ('Amy', 30), ('Liam', 40)
)
SELECT summary.customer, summary.total_orders, summary.total_amount
FROM (
  SELECT customer, COUNT(*) AS total_orders, SUM(amount) AS total_amount
  FROM orders GROUP BY customer
) AS summary
WHERE summary.total_orders >= 2
ORDER BY summary.customer;
Verified result of the self-contained case
customertotal_orderstotal_amount
Amy250

order_total is now an ordinary column in the outer query. The filter does not remove any orders before they are counted.

Check your interpretation: If you change the threshold to 1, why should Liam appear as well?

Show answer

Because the outer filter compares the count that has already been calculated: with order_total >= 1, Liam's summary (one order) also meets the condition. Amy and Liam would appear.

Technical questions: PostgreSQL: Table Expressions and Joins (opens in a new tab).