Logical order of the clauses
| Stage | Operation | Question it answers |
|---|---|---|
| 1 | FROM, JOIN and ON | Where do the rows come from and how are they related? |
| 2 | WHERE | Which rows meet the condition before grouping? |
| 3 | GROUP BY and aggregations | Which groups are formed and what is calculated for each? |
| 4 | HAVING | Which groups meet the condition? |
| 5 | Window functions and SELECT expressions | Which values are calculated for the output rows? |
| 6 | DISTINCT | Are identical output rows removed? |
| 7 | ORDER BY | In what order is the result returned? |
| 8 | LIMIT, FETCH or TOP, depending on the engine | Which part of the result is kept? |
This outline covers a single SELECT block. Queries with set operations, subqueries or engine-specific clauses mean thinking about each of their blocks. In a LEFT JOIN, unmatched rows are kept before the WHERE filter runs, which is why moving a condition between ON and WHERE can change the result.
The usual written order starts with SELECT, followed by FROM, WHERE, GROUP BY, HAVING and ORDER BY. Stick to that syntax even if you explain the query starting from the table.
Example
We want the category with the highest paid amount, provided it reaches at least 100 units. The amounts in this demo are whole numbers so we can focus on the clauses. Run the setup once on a test SQLite connection.
CREATE TABLE sales_sort_order_demo (
id INTEGER PRIMARY KEY,
category TEXT NOT NULL,
amount INTEGER NOT NULL,
status TEXT NOT NULL
);
INSERT INTO sales_sort_order_demo (id, category, amount, status) VALUES
(1, 'Books', 40, 'paid'),
(2, 'Books', 70, 'paid'),
(3, 'Books', 200, 'cancelled'),
(4, 'Courses', 120, 'paid'),
(5, 'Courses', 30, 'paid'),
(6, 'Material', 25, 'paid');SELECT category, SUM(amount) AS total
FROM sales_sort_order_demo
WHERE status = 'paid'
GROUP BY category
HAVING SUM(amount) >= 100
ORDER BY total DESC, category
LIMIT 1;1. FROM: we start with six rows
The source is sales_sort_order_demo. Each row is a sale, not a category. The cancelled sale exists in the original data and must be discarded before adding up.
2. WHERE: five paid sales remain
The row with id = 3 drops out of the logical set because its status is cancelled. Its 200 units must not inflate the Books total. Rows 1, 2, 4, 5 and 6 remain.
3. GROUP BY and SUM: three groups are formed
| category | SUM(amount) |
|---|---|
| Books | 110 |
| Courses | 150 |
| Material | 25 |
The two Books rows contribute 40 + 70. The two Courses rows contribute 120 + 30. Material contributes only 25. The status column has already done its job as a filter on individual sales.
4. HAVING: two categories survive
The condition applies to each group's total. Courses and Books clear the threshold of 100; Material is left out. Using WHERE amount >= 100 would ask for something else: it would discard small sales before calculating the total.
5. SELECT, ORDER BY and LIMIT: we get one row
The output shows category and the sum with the alias total. It is sorted first by that total, highest first, and then by category to break ties. The limit keeps one row.
| category | total |
|---|---|
| Courses | 150 |
Aliases, window functions and the physical plan
Why a SELECT alias does not always work in WHERE
In PostgreSQL and SQL Server, an alias defined in the SELECT list cannot be used as if it were an input column in the WHERE clause of the same block. The portable approach is to repeat the expression, or compute it in a subquery or CTE and filter from outside. In ORDER BY, however, you can use the output alias.
Dialects also differ: MySQL allows aliases in HAVING; PostgreSQL supports some uses in GROUP BY; SQLite accepts alias extensions that are best not carried over without checking. In our example we use HAVING SUM(amount) >= 100, which makes the intent explicit without relying on that extension. See the guide on aliases that do not work in WHERE to fix that error.
Nor does an alias turn an aggregate into a row condition. If you want to compare a per-category total, use HAVING or filter the grouped result in an outer block. Choosing WHERE or HAVING changes what you are filtering, not just how you write the name.
Where ROW_NUMBER and other window functions come in
A window function receives the rows that survived the filters and, if there is grouping, the groups. To keep a position calculated with ROW_NUMBER(), compute the position in an inner block and then filter in the outer block. That is the pattern documented by PostgreSQL for filtering window function results (opens in a new tab).
WITH ranked AS (
SELECT id, category, amount,
ROW_NUMBER() OVER (
PARTITION BY category
ORDER BY amount DESC, id
) AS position
FROM sales_sort_order_demo
WHERE status = 'paid'
)
SELECT id, category, amount
FROM ranked
WHERE position = 1
ORDER BY category;| id | category | amount |
|---|---|---|
| 4 | Courses | 120 |
| 2 | Books | 70 |
| 6 | Material | 25 |
This time Material does appear: this query looks for one sale per category and does not require a minimum total of 100. The inner filter discards cancelled sales before numbering, so row 3 cannot win for Books. The tiebreaker on id stops two equal amounts from producing an ambiguous choice.
If you numbered every sale and only discarded the cancelled ones afterwards, the row picked for Books could be the cancelled 200; removing it would lose the category altogether. Following the two blocks separately makes that difference clear.
Logical order, physical plan and engine differences
To find out whether a query uses indexes, a table scan or a sort, look at its execution plan. The logical outline does not tell you how many times a table is read or whether a CTE is materialised. Nor does it guarantee that the conditions in a WHERE are evaluated from left to right.
Do not protect a division by assuming that denominator <> 0 will always be evaluated before another condition that divides. Write the calculation safely, for example with NULLIF, and check the result when the divisor is zero.
| Engine | Single-row limit | Window functions |
|---|---|---|
| SQLite | LIMIT 1 | ROW_NUMBER available since 3.25.0. |
| PostgreSQL | LIMIT 1 or FETCH FIRST 1 ROW ONLY | CTEs and ROW_NUMBER supported. |
| MySQL 8.0+ | LIMIT 1 | CTEs and ROW_NUMBER supported. |
| SQL Server | SELECT TOP (1) at the start of the select list | CTEs and ROW_NUMBER supported; end the previous statement with a semicolon. |
To adapt the first query to SQL Server, write SELECT TOP (1) category, SUM(amount) AS total, keep ORDER BY and remove LIMIT. The downloadable examples use SQLite syntax. If your engine adds QUALIFY or other clauses, check its own logical order.
How to check it
SELECT category, SUM(amount) AS total
FROM sales_sort_order_demo
WHERE status = 'paid'
GROUP BY category
HAVING SUM(amount) >= 100
ORDER BY total DESC, category;The result is Courses, 150 followed by Books, 110. We remove LIMIT; WHERE still filters sales and HAVING still filters groups. There is no need to change the threshold or move it to another clause.