SQL Playgroundlearn SQL safely, in your browser

How to Read Any SQL Query, Clause by Clause

A query reads left to right but executes in a different order. Knowing that order turns a wall of keywords into a sentence you can follow, and it explains most "why did this return that?" moments.

It executes in a different order than it is written

You write SELECT first, but the database runs FROM first: it finds the rows, then filters them with WHERE, then groups with GROUP BY, then filters the groups with HAVING, then computes SELECT, then sorts with ORDER BY, and finally trims with LIMIT.

That is why you cannot use a SELECT alias inside WHERE — at the moment WHERE runs, the alias does not exist yet. ORDER BY can use it because it runs afterwards.

Start at FROM

Find the table or join. Everything else is a filter or a transformation applied to that row set. If the query joins four tables, sketch them and the join keys before reading a single column name — the shape of the data explains the rest.

Then WHERE narrows the rows

Every condition joined by AND must hold. A condition joined by OR widens the result, which is the most common cause of "it returned too many rows": WHERE a = 1 OR b = 2 AND c = 3 does not mean what it looks like. Parenthesise: WHERE a = 1 OR (b = 2 AND c = 3).

GROUP BY collapses, HAVING filters the collapse

After GROUP BY you no longer have rows, you have groups. COUNT, SUM, AVG operate on a group. HAVING is the WHERE that runs after grouping — "groups with more than three rows" is HAVING COUNT(*) > 3.

ORDER BY and LIMIT are last

Sorting happens after the result is computed, so it can be the most expensive clause on a large table if no index supports it. LIMIT without ORDER BY returns an arbitrary subset — not the "first" rows, because SQL tables have no inherent order.

Try it in the playground — free and private

← All SQL guides