SQL order of execution: how the database reads your query

You type SELECT first, but the database gets to it halfway through. Once you know the real order, a lot of puzzling errors make sense: why WHERE refuses COUNT, why an alias works in ORDER BY but not in WHERE, and when HAVING is the right tool.

In short: you write SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY … LIMIT. The logical order of evaluation is FROM (with JOIN), WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, LIMIT. Each step only sees what the steps before it produced.

Before you start: GROUP BY, HAVING and ORDER BY. You'll only need JOIN for the third exercise.

Try it now

A typical request: who handled how many delivered orders? Before you type, decide whether the status check has to happen before or after counting.

Task Only delivered orders count toward this quarter's bonus. Show employee_id and the number of orders with status 'delivered' that each person handled.

orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

The order the database works in

On the left is the order you write the clauses in. On the right is the order the database evaluates them in, logically speaking. Follow the lines to see where each clause ends up.

Written order on the left: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. Execution order on the right: 1 FROM and JOIN, 2 WHERE, 3 GROUP BY, 4 HAVING, 5 SELECT, 6 DISTINCT, 7 ORDER BY, 8 LIMIT. The order you write The order it runs SELECT (DISTINCT)FROM / JOIN WHEREGROUP BY HAVINGORDER BY LIMIT 1 FROM / JOIN2 WHERE 3 GROUP BY4 HAVING 5 SELECT6 DISTINCT 7 ORDER BY8 LIMIT
  1. FROM and JOIN: the database fetches the tables and joins them into one big working table.
  2. WHERE: tests every row on its own and throws away the ones that fail. There are no groups yet.
  3. GROUP BY: collapses the remaining rows into groups. From here on, COUNT, SUM and friends work per group.
  4. HAVING: tests whole groups, for example COUNT(*) >= 2.
  5. SELECT: computes the columns you asked for and applies the AS names.
  6. DISTINCT: removes duplicate result rows (more on DISTINCT).
  7. ORDER BY: sorts the finished result. The SELECT names are known by now.
  8. LIMIT: trims the list at the very end.

This is the logical order. Internally the optimizer may take shortcuts, as long as the result is the same. Both Microsoft's and SQLite's documentation point this out. For reading results and error messages, though, the logical order is the one that matters.

One query, step by step

Purchasing asks: which categories have at least two products under 100, and what is the most expensive of them?

SELECT category, COUNT(*) AS products, MAX(price) AS top_price
FROM products
WHERE price < 100
GROUP BY category
HAVING COUNT(*) >= 2
ORDER BY top_price DESC;
categoryproductstop_price
Printer supplies289.9
Writing26.99
Paper25.49

FROM starts with all 12 products. WHERE keeps the 7 that cost less than 100, so Furniture and Electronics are gone before any grouping happens. GROUP BY turns those 7 rows into 4 groups: Filing, Paper, Printer supplies and Writing. HAVING drops Filing, which has only one product left. Only now does SELECT work out products and top_price, and ORDER BY can sort by that name.

Why an alias works in ORDER BY but not in WHERE

An alias is born in step 5, in SELECT. ORDER BY runs later and can use it. WHERE runs in step 2, before the alias exists. This version works in MySQL, PostgreSQL and SQL Server alike:

SELECT name, price * stock AS stock_value
FROM products
WHERE price * stock > 2000
ORDER BY stock_value DESC;
namestock_value
27-inch monitor4185
Comfort office chair2268
Standing desk2245
Copy paper, 500 sheets2095.8

WHERE repeats the calculation; ORDER BY just uses the name. The exercises on this site run on SQLite, which happens to accept WHERE stock_value > 2000 as well. Don't get used to it: PostgreSQL, SQL Server and MySQL all reject that exact query.

More practice: filtering before and after grouping

This one needs both kinds of filter. One tests single products, the other tests whole categories.

Task Purchasing wants to know which categories have at least two products in stock (stock greater than 0). Show category and the number of those products, only for categories with at least two of them.

products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

To finish, the whole pipeline in one query: join, filter, group, compute, sort, cut.

Task Management wants to see the three customers with the highest revenue, counting delivered orders only (status 'delivered'). Show name and revenue (the sum of quantity times unit_price), highest revenue first.

customers 12 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164
orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
order_items 38 rows, 4 columns
order_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.9

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Common mistakes

A row condition in HAVING instead of WHERE

GROUP BY employee_id HAVING status = 'delivered' looks innocent but gives wrong counts. COUNT(*) has already counted every order, and SQLite checks the status against just one row of each group. In the first exercise the checker answers "Your query returns only 3 rows. Wanted: 4 rows. Is a column missing from GROUP BY, or is a condition in WHERE or HAVING too strict?" MySQL with its default ONLY_FULL_GROUP_BY setting and PostgreSQL won't run the query at all; the SQLite documentation describes these "bare columns" as an SQLite-specific extension.

COUNT or SUM in WHERE

WHERE COUNT(*) >= 2 can't work, because there are no groups yet when WHERE runs. The exercise tells you: "Functions like COUNT or SUM do not work in WHERE, because WHERE checks single rows. Conditions on groups go in HAVING."

Writing the clauses in execution order

The execution order is a way of thinking, not a way of writing. … GROUP BY category WHERE price < 100 is a syntax error near "WHERE", and the exercise reminds you of the written order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.

Expecting LIMIT to trim the raw data

LIMIT 3 does not mean "take three orders and then add them up". It applies after GROUP BY and ORDER BY. Leave out ORDER BY and you get three arbitrary groups; the checker then says that not every value matches.

Order and aliases in MySQL, PostgreSQL, SQL Server and SQLite

The logical order is the same everywhere. Where the products differ is how early a SELECT alias may be used:

DatabaseAlias in WHEREin GROUP BYin HAVINGin ORDER BY
MySQLnoyesyesyes
PostgreSQLnoyesnoyes
SQL Servernononoyes
SQLite (these exercises)runsrunsrunsyes

The MySQL manual explains the WHERE ban with exactly this order: when WHERE is evaluated, the column value may not be known yet. Microsoft lists the SQL Server steps as FROM, ON, JOIN, WHERE, GROUP BY, WITH CUBE or WITH ROLLUP, HAVING, SELECT, DISTINCT, ORDER BY, TOP, and states that a SELECT alias is only visible to later clauses such as ORDER BY. In SQL Server the last step is TOP rather than LIMIT. For SQLite, only the ORDER BY case is documented; that WHERE, GROUP BY and HAVING accept an alias too is something we tested in the exercises. If a query has to run anywhere, spell the expression out in WHERE and HAVING.

Sources: Microsoft Learn (SELECT, logical processing order), PostgreSQL documentation (SELECT), MySQL Reference Manual (Problems with Column Aliases), sqlite.org (SELECT).

FAQ

Does the database really run the steps one after another?

Not necessarily. The optimizer may use an index or test a condition earlier. The result, however, has to look as if the steps ran in the logical order, which is why that order is the right tool for explaining results and errors.

How do I choose between WHERE and HAVING?

If the condition is about a single row (status, price, date), use WHERE. If it is about a group (a count, a total, an average), use HAVING. WHERE also keeps unneeded rows out of the groups in the first place.

Where does WITH fit in?

Right at the start. According to the PostgreSQL documentation, the queries in the WITH list are computed first and can then be used in FROM like tables.

Can I sort by a column that is not in SELECT?

Yes. ORDER BY can use any column of the tables in FROM, even one you don't display.

Up next: SQL for Excel users

VLOOKUP, SUMIFS, PivotTables, IF: you already know these jobs from Excel. Next you'll see what the same jobs look like in SQL, and when switching is worth it.

Practice SQL for Excel users

Write to us

Choose language

Select your preferred language