Sub topic 7
The logical order of query evaluation
This chapter assumes you can write SELECT, FROM, WHERE and ORDER BY queries and have met GROUP BY and aggregate functions such as SUM and COUNT. The examples use an orders table with the columns order_id, customer_id, amount and status.
Written order versus logical order
You write a query starting with SELECT. The database does not start there. SQL defines a logical order of evaluation, a sequence of steps that determines which names and values each clause can see. Many confusing errors come from the gap between the two orders.
| Step | Clause | What happens |
|---|---|---|
| 1 | FROM and JOIN | Build the working set of rows from the tables |
| 2 | WHERE | Discard individual rows that fail the condition |
| 3 | GROUP BY | Sort the surviving rows into groups |
| 4 | Aggregates | Compute COUNT, SUM, AVG, MIN and MAX for each group |
| 5 | HAVING | Discard whole groups that fail the condition |
| 6 | SELECT | Compute the output expressions, assign aliases, evaluate window functions |
| 7 | DISTINCT | Remove duplicate output rows |
| 8 | ORDER BY | Sort the output rows |
| 9 | LIMIT / OFFSET (FETCH FIRST) | Keep only the requested slice |
A clause can only use what earlier steps have produced. Most of this chapter follows from that rule.
Tracing a query step by step
Take this data.
| order_id | customer_id | amount | status |
|---|---|---|---|
| 1 | 1 | 500 | paid |
| 2 | 1 | 700 | paid |
| 3 | 1 | 200 | refunded |
| 4 | 2 | 300 | paid |
| 5 | 2 | 100 | paid |
| 6 | 3 | 1500 | paid |
Now run this query.
SELECT customer_id,
SUM(amount) AS total
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING SUM(amount) > 1000
ORDER BY total DESC
LIMIT 1;Here is what happens at each step.
- FROM supplies all six rows.
- WHERE removes order 3, which is refunded. Five rows remain.
- GROUP BY forms three groups: customer 1 with orders 1 and 2, customer 2 with orders 4 and 5, and customer 3 with order 6.
- Aggregates compute the sums: 1200, 400 and 1500.
- HAVING keeps the groups with a sum above 1000: customers 1 and 3.
- SELECT produces the output columns
customer_idandtotal. The aliastotalnow exists. - ORDER BY can use
totalbecause the alias was created in step 6. The order is customer 3 (1500), then customer 1 (1200). - LIMIT keeps the first row: customer 3.
Because WHERE ran before grouping, the refunded order never reached the sum. If it had, customer 1's total would be 1400, a different number.
What the order explains
Aggregates are not allowed in WHERE
WHERE runs at step 2, before any group exists, so no aggregate value exists yet. This query fails.
SELECT customer_id
FROM orders
WHERE SUM(amount) > 1000
GROUP BY customer_id;Move the condition to HAVING, which runs after the aggregates are computed.
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 1000;Column aliases are not visible in WHERE
An alias is created in step 6, so WHERE at step 2 cannot see it. This fails with an "unknown column" style error.
SELECT amount * 2 AS doubled
FROM orders
WHERE doubled > 1000;Repeat the expression, or wrap the query in a subquery.
SELECT doubled
FROM (
SELECT amount * 2 AS doubled
FROM orders
) AS t
WHERE doubled > 1000;ORDER BY runs after SELECT, so it can use aliases. That is why ORDER BY total DESC worked in the trace.
The SELECT list sees only grouped data
After step 3 the engine no longer has individual rows, only groups. A column in the SELECT list must therefore be a grouping column, an expression built from grouping columns, or an aggregate over the group's rows. Selecting a plain status in a query grouped only by customer_id fails because a customer's group can hold several different statuses and the output allows one value per group. The next chapters cover this rule in detail.
Window functions run late
Window functions are evaluated in step 6, after grouping and HAVING. They can see the grouped result but cannot be used in WHERE, GROUP BY or HAVING. To filter on a window result, compute it in a subquery and filter in the outer query.
SELECT *
FROM (
SELECT order_id,
customer_id,
amount,
SUM(amount) OVER (PARTITION BY customer_id) AS customer_total
FROM orders
) AS t
WHERE customer_total > 1000;The subquery is evaluated first. The outer WHERE then treats customer_total as an ordinary column.
ORDER BY can use things SELECT does not show
ORDER BY runs after grouping, so it may sort by an aggregate that is not in the SELECT list.
SELECT customer_id
FROM orders
GROUP BY customer_id
ORDER BY SUM(amount) DESC;This returns customer ids ordered by their total, without showing the total. One exception applies. With SELECT DISTINCT, ORDER BY expressions generally must appear in the select list, because duplicates are removed before sorting.
Choosing between WHERE and HAVING
A condition on a grouping column can be written in either clause, and the result is the same. This query is valid.
SELECT status, COUNT(*) AS order_count
FROM orders
GROUP BY status
HAVING status = 'paid';Prefer WHERE for such conditions.
SELECT status, COUNT(*) AS order_count
FROM orders
WHERE status = 'paid'
GROUP BY status;Filtering early means fewer rows to group, and many optimizers can also use an index for the WHERE condition. Reserve HAVING for conditions that depend on an aggregate. The rule of thumb is that WHERE answers "which rows count?" and HAVING answers "which groups are worth keeping?".
Edge cases from the evaluation order
Aggregates without GROUP BY
If a query has aggregates but no GROUP BY, all remaining rows form one group. That group exists even when no rows survive WHERE.
SELECT COUNT(*) AS n, SUM(amount) AS total
FROM orders
WHERE status = 'cancelled';If no order is cancelled, this returns one row: n is 0 and total is NULL. COUNT returns 0 for an empty group, while SUM, AVG, MIN and MAX return NULL. Wrap the sum in COALESCE(SUM(amount), 0) if you need a zero.
GROUP BY with empty input
With GROUP BY, an empty input produces no groups, so the result has zero rows.
SELECT customer_id, COUNT(*) AS n
FROM orders
WHERE status = 'cancelled'
GROUP BY customer_id;Compare the two empty cases. Without GROUP BY you get one row of zero or NULL values. With GROUP BY you get nothing. Application code that expects a row can break on this difference.
HAVING without GROUP BY
HAVING with no GROUP BY treats the whole table as a single group. The query returns either one row or none, depending on whether that group passes the test.
SELECT SUM(amount) AS total
FROM orders
HAVING SUM(amount) > 1000;This is valid in PostgreSQL, MySQL and SQL Server. It is rarely the clearest way to write the query.
LIMIT comes last
LIMIT applies after sorting. ORDER BY total DESC LIMIT 1 returns the top group. Without ORDER BY, LIMIT returns an arbitrary row, because SQL guarantees no row order unless you ask for one.
Logical order is not physical order
The logical order defines what result the query must produce. It does not dictate how the engine works. An optimizer may filter earlier, reorder joins, or use an index to compute a MIN, as long as the result matches the logical model. Two practical consequences follow.
- Reason about correctness with the logical order. Reason about speed with the query plan, for example the output of
EXPLAIN. - Do not rely on side effects such as which expression is evaluated first. A condition such as
WHERE denominator <> 0 AND numerator / denominator > 1is not guaranteed to short-circuit in every database.
Quick diagnosis table
| Symptom | Likely cause | Fix |
|---|---|---|
| "aggregate functions are not allowed in WHERE" | Aggregate used before grouping | Move the condition to HAVING |
| "unknown column" for an alias in WHERE | Alias created after WHERE runs | Repeat the expression or use a subquery |
| Totals include rows you meant to exclude | Condition placed after the aggregate, or missing from WHERE | Filter in WHERE before GROUP BY |
| Window function rejected in WHERE | Window functions run after HAVING | Compute in a subquery, filter outside |
| Query returns no row where you expected a zero | GROUP BY over empty input | Remove GROUP BY or add the missing groups from another table |
Exercise
A query groups orders by customer_id and uses WHERE SUM(amount) > 1000. It fails. Rewrite the condition so the query runs, and say which step of the evaluation order makes the original invalid.
Show answer
Replace WHERE with HAVING: GROUP BY customer_id HAVING SUM(amount) > 1000. WHERE runs at step 2, before groups are formed and before aggregates are computed, so SUM(amount) does not exist yet. HAVING runs after the aggregates are computed.
Exercise
Using the six-row orders table from this chapter, what does SELECT customerid, COUNT(*) AS n FROM orders WHERE status = 'paid' GROUP BY customerid HAVING COUNT(*) >= 2 ORDER BY n DESC return?
Show answer
Customer 1 with n = 2 and customer 2 with n = 2 (the order between them is not defined). WHERE leaves orders 1, 2, 4, 5 and 6. Grouping gives counts of 2, 2 and 1 for customers 1, 2 and 3. HAVING removes customer 3, whose count is 1.
Exercise
SELECT COUNT(*) AS n, SUM(amount) AS total FROM orders WHERE status = 'cancelled' runs against a table with no cancelled orders. How many rows come back, and what are the values? What changes if you add GROUP BY customer_id?
Show answer
One row comes back with n = 0 and total = NULL, because with no GROUP BY the empty input still forms a single group. With GROUP BY customer_id there are no groups, so the result has zero rows.