skip to today's puzzle

Every query is written in the same order

You always write the parts of a query in this order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT. Use only the ones you need, but keep them in that order, or the database won't understand. Good to know: the database reads them differently. It starts with FROM, then filters and groups, and only works out SELECT near the end.

A tiny example

In plain English: Read a query in this order: what to show, where from, which rows, how to group, which groups, how to sort, how many to keep.

SELECT →
FROM →
WHERE →
GROUP BY →
HAVING →
ORDER BY →
LIMIT

Common questions

Why can't I use a SELECT alias in WHERE?
The database works out WHERE before SELECT, so an alias made in SELECT doesn't exist yet when WHERE runs. Repeat the expression in WHERE instead.
In what order does the database run a query?
Roughly: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. That's why ORDER BY can usually use a SELECT alias, but WHERE can't.

Related SQL lessons

Ready for a break?

A fresh, bite-sized SQL puzzle waits every morning. Tap tiles, see real results. No terminal, no setup, no timers.

Try today's free SQL puzzle