QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › SELECT and filtering

In what order is a query actually executed?

A query is processed in a logical order: FROM and JOIN, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT. Each step sees only the result of the earlier ones, so an alias from SELECT is visible in ORDER BY but not in WHERE, and a condition on an aggregate goes in HAVING. This is a model, not the literal plan: the planner chooses the physical order.

SQL · SELECT and WHERE

The same alias fails in WHERE and works in ORDER BY. Why does SQL not read a query the way it is written?

You compute an amount in dollars, name it amount_usd and immediately filter WHERE amount_usd > 100. The database says there is no such column, although it was just written in SELECT. The next line with the same alias in ORDER BY works. This lesson explains the logical order in which a query is processed: it answers "why is the alias visible here but not there" and "why can an aggregate not go in WHERE".

How it works and why. The SQL standard defines a query as a pipeline in which each step takes a table and returns a table. The next step sees only what the earlier ones created. The order is: FROM and JOIN build rows, WHERE drops rows, GROUP BY merges them into groups, HAVING drops groups, SELECT computes expressions and sets aliases, DISTINCT removes duplicates, ORDER BY sorts, LIMIT with OFFSET cut. Window functions (OVER) are computed between HAVING and the final SELECT, so they cannot go in WHERE either.

The logical processing order

1 FROM / JOINbuilds rows and pairs2 WHEREdrops rows, no aliases yet3 GROUP BYrows merge into groups4 HAVINGdrops groups, sees aggregates5 SELECTcomputes expressions, sets aliases6 DISTINCTremoves duplicate result rows7 ORDER BYsorts, sees SELECT aliases8 LIMIT / OFFSETcuts the sorted result
Figure 1. The alias appears at step 5, so WHERE (step 2) does not see it and ORDER BY (step 7) does.

This is a logical model, not what the server literally does. The planner freely changes the physical steps: it pushes a filter before a JOIN, uses an index, sorts by an index. It is only obliged to return the same result as if the steps ran in the logical order. For a tester the model is useful twice: it explains query errors and tells where to put a condition so that it means what you need.

Example: from an error to a working query.

-- an illustrative rate of 0.25; the alias does not exist in WHERE yet
SELECT amount * 0.25 AS amount_usd
FROM transactions
WHERE amount_usd > 100;
-- PostgreSQL: ERROR: column "amount_usd" does not exist

Step 2 (WHERE) runs before step 5 (SELECT), where amount_usd is born, so the name does not exist in WHERE yet. There are two ways out:

-- option 1: repeat the expression
SELECT amount * 0.25 AS amount_usd
FROM transactions
WHERE amount * 0.25 > 100
ORDER BY amount_usd DESC;   -- the alias is visible here

-- option 2: compute in a subquery and filter outside
SELECT *
FROM (SELECT id, amount * 0.25 AS amount_usd FROM transactions) x
WHERE amount_usd > 100;

The same goes for aggregates. A sum exists only after grouping (step 3), and WHERE works at step 2, so a condition on an aggregate is written in HAVING:

-- an aggregate in WHERE: rows are not grouped yet
SELECT user_id FROM transactions
WHERE SUM(amount) > 1000 GROUP BY user_id;
-- PostgreSQL: ERROR: aggregate functions are not allowed in WHERE

SELECT user_id FROM transactions
GROUP BY user_id
HAVING SUM(amount) > 1000;

Where to put the condition

step 2

WHERE

A filter on individual rows before grouping. Sees no aggregates and no aliases. Shrinks the input of GROUP BY, so it is usually faster.

step 4

HAVING

A filter on groups after grouping. Sees aggregates (SUM, COUNT). A condition on a plain column is better not placed here.

Figure 2. A condition that does not need an aggregate belongs in WHERE: rows are dropped before they are grouped.

Limits and alternatives. Dialects relax the rules in different ways, and you should not rely on it. PostgreSQL and MySQL allow an alias in GROUP BY, MySQL also in HAVING, SQL Server accepts an alias only in ORDER BY. Even where an alias is allowed in ORDER BY, it has to be a standalone name: in PostgreSQL ORDER BY amount_usd works while ORDER BY amount_usd + 1 does not, you must repeat the expression. If you need an alias in a filter, the reliable path is a subquery or a CTE (WITH), as in option 2. For conditions around a LEFT JOIN the order matters even more: a condition in ON works at step 1 and in WHERE at step 2, and the results differ (a separate lesson covers it). The real execution plan (it differs from the logical one) is shown by EXPLAIN.

Common mistakes.

  • A SELECT alias in WHERE: "column does not exist".
  • An aggregate in WHERE instead of HAVING: "aggregate functions are not allowed in WHERE".
  • A condition on a grouping column in HAVING: it works but drops less before grouping and reads confusingly.
  • Assuming the server runs the query in written order or literally in logical order: it is a model of meaning, not a plan.
  • Relying on an alias in GROUP BY or HAVING because "it works in MySQL": another database will fail the query.

Check yourself

Why is a SELECT alias visible in ORDER BY but not in WHERE?

Answer

ORDER BY runs after SELECT (step 7 versus step 5), when the alias already exists. WHERE runs at step 2, before SELECT, so the alias is not there yet.

How do you keep only users whose transactions sum to more than 1000?

Answer

Group by user_id and put the condition on the aggregate in HAVING: GROUP BY user_id HAVING SUM(amount) > 1000. An aggregate does not work in WHERE because the groups do not exist at that stage.

A query with GROUP BY user_id has WHERE status = 'completed' and HAVING SUM(amount) > 500. In what order are they applied?

Answer

First WHERE drops the rows that are not completed, then they are grouped, then HAVING drops the groups where the sum of the completed ones is below 500. Simply moving the status condition into HAVING does not work: status is not in GROUP BY, so PostgreSQL rejects the query. A condition on rows belongs in WHERE.

In an interview. Junior: FROM and JOIN run first, then WHERE, GROUP BY, HAVING, and only then SELECT, ORDER BY and LIMIT. That is why a SELECT alias cannot be used in WHERE but can be in ORDER BY, and why aggregates are filtered through HAVING. Middle/Senior: It is the logical order from the standard: each step sees only the result of the previous ones. The physical order is chosen by the planner and visible in EXPLAIN, but the result must match the logical model. If I need an alias in a filter, I move the computation into a subquery or a CTE instead of relying on one database's extension.

More articles in this chapter