SQL Query Fundamentals
Read SQL the way the engine does
SELECT, FROM, WHERE, ORDER BY, LIMIT and projections are the backbone of every query you will ever write — and the order they execute in explains most query surprises.
What you will learn
- Write correct SELECT/WHERE/ORDER BY/LIMIT queries
- Understand logical execution order (FROM → WHERE → SELECT → ORDER)
- Avoid the classic scope traps that surprise new SQL writers
What is this?
A query requests rows from tables and narrows them: FROM names the table, WHERE filters rows, SELECT picks columns, ORDER BY sorts, LIMIT bounds. The logical order of operations — FROM, then WHERE, then SELECT, then ORDER BY — explains why aliases can't be used in WHERE and why filtering happens before sorting.
Why do you need it?
- SQL is the interface to every warehouse, lakehouse and OLAP engine; it is the lingua franca of data roles.
- Understanding execution order turns confusing plan behavior into predictable logic.
- A correctly scoped query is the difference between a correct report and a silently miscounted one.
Mental model
Grocery shopping as a checklist
A SQL query
You enter the store (FROM), skip aisles that don't match the list (WHERE), take only the items you need (SELECT), arrange them on the belt by aisle (ORDER BY), and the cashier handles at most 10 items (LIMIT).
How it works
- FROM picks the source row set (table or subquery/CTE).
- WHERE tests each row and keeps only matches — no ordering, no aliases from SELECT yet.
- SELECT computes the output columns and expressions, including aliases.
- GROUP BY/HAVING (if present) run between WHERE and SELECT for row collapsing.
- ORDER BY sorts the final result; LIMIT/OFFSET trims it last.
Logical execution order of a SELECT.
Key commands
SELECT * FROM orders WHERE region = 'EU' ORDER BY ts DESC LIMIT 10;Latest 10 EU orders.
SELECT DISTINCT region FROM orders;Unique regions.
SELECT COUNT(*) FROM orders;Total row count.
Examples
The canonical query anatomy
SELECT country, COUNT(*) AS ordersFROM salesWHERE amount > 0GROUP BY countryORDER BY orders DESCLIMIT 5;Rows are filtered, grouped, counted, then sorted and capped — reading top to bottom mirrors execution only roughly; the engine actually goes FROM → WHERE → GROUP → SELECT → ORDER.
In production
- A daily revenue query filters to today's window, groups by channel, and orders before the BI tool paginates.
- An audit script SELECTs row counts per source with WHERE clauses matching table partitions.
- A paginated admin export uses ORDER BY id + LIMIT/OFFSET (or keyset) to walk a large table.
Best practices
- Select explicit columns, not `*`, so renames don't silently break consumers.
- Filter in WHERE, not after fetching — push predicates to the engine.
- Write WHERE against raw columns, not SELECT aliases (aliases aren't in scope).
- Always ORDER BY a deterministic key when paginating.
Common mistakes
- Using a SELECT alias inside WHERE — it isn't defined yet and errors.
- Assuming WHERE filters before GROUP BY math — that's what HAVING is for.
- Forgetting that NULL comparisons in WHERE need IS NULL, silently dropping rows.
Common issues
Query 'works' but returns zero rowsWHERE compared a numeric column to a string that never matches
Coerce the predicate with CAST and verify a sample row actually satisfies it.
ORDER BY says column doesn't existReferencing a SELECT alias the engine resolves out of scope
Repeat the expression in ORDER BY or use a derived table/CTE.
Debugging tips
- Simplify: comment out GROUP BY/ORDER pieces until the row set looks right.
- Check row counts first; a WHERE that matches nothing looks suspiciously like 'empty success'.
- Re-read the predicate against sample data — a `19.99` string vs `19.99` number mismatch is common.
Interview checkpoint
Hands-on lab
- Create a small schema and seed data
- Write filtered, ordered, bounded queries
- Prove execution order with a WHERE-alias trap
Scaffold a Practice Database and Write Your First Queries
25 min · beginner
Quick quiz
Which clause executes before SELECT in the logical order?
A SELECT alias can be referenced inside the WHERE clause of the same query.