Lesson 2
SELECT, WHERE, and ORDER BY
Read the core shape of everyday SQL queries.
Most everyday SQL starts with a simple shape:
SELECT id, email, created_at
FROM users
WHERE status = 'active'
ORDER BY created_at DESC
LIMIT 50;
Read it in layers:
SELECTsays which columns appear in the result.FROMsays the starting table.WHEREremoves rows that do not match conditions.ORDER BYcontrols result order.LIMITcaps how many rows come back.
This order is easy to read, but databases do not necessarily execute it line by line. The database optimizer can choose indexes and reorder internal work. For debugging, your first job is still to understand the logical meaning.
Be careful with filters
Small filter changes can change behavior dramatically:
WHERE status = 'paid'
AND created_at >= '2026-01-01'
This means both conditions must be true. If you use OR, rows can match either side:
WHERE status = 'paid'
OR status = 'refunded'
When a query is wrong, isolate filters one at a time. Ask: which condition removes the row I expected to see?
Ordering is not guaranteed without ORDER BY
Tables do not have a stable natural order that application code should depend on. If an endpoint says "latest users", the query should express that with ORDER BY created_at DESC. Without it, results can appear stable in development and change later after indexes, upgrades, or data growth.
Key takeaway
For simple queries, debug from FROM to WHERE to ORDER BY. Confirm the source rows first, then add filters, then add sorting and limits.
Use the SQL Formatter to split a one-line query into readable clauses before you inspect filters.