SQL Query Basics Cheatsheet
SELECT, WHERE, ORDER BY, and LIMIT at a glance.
The skeleton
select col_a, col_b -- which columns
from some_table -- which table
where condition -- which rows
order by col_a desc -- in what order
limit 10 -- how many Logical clause order
SQL is written in one order but reasoned about in a different logical order:
rows come from FROM, are filtered by WHERE,
grouped, filtered again by HAVING, then projected by
SELECT before final ordering and limiting. Dialects can add
conveniences on top of that model: DuckDB, for example, lets many
SELECT aliases be reused in WHERE,
GROUP BY, and HAVING. Each step is worked through
on SQL order of execution.
| Written | Logical order |
|---|---|
| SELECT | 5 (logical) |
| FROM | 1 (logical) |
| WHERE | 2 (logical) |
| GROUP BY | 3 (logical) |
| HAVING | 4 (logical) |
| ORDER BY | 6 (logical) |
| LIMIT | 7 (logical) |
Choosing columns
| Goal | SQL |
|---|---|
| Every column | select * |
| Specific columns | select name, price |
| Rename a column | select price as cost |
| Computed column | select price * 1.06 as with_tax |
| Drop duplicates | select distinct city |
Filtering with WHERE
| Operator | Matches |
|---|---|
= <> | Equal / not equal |
< <= > >= | Comparisons (numbers, dates, text) |
between a and b | Inclusive range |
in (1, 2, 3) | Any value in a list |
like 'a%' | Pattern: % = any run, _ = one char |
is null / is not null | Missing / present |
and or not | Combine conditions (use parentheses) |
Sorting & limiting
order by order_date desc, order_id -- tiebreak keeps it stable
limit 5 = never matches NULL, even
null = null is unknown. Use is null, or
is distinct from for a null-safe "not equal".
Related
Understand tables, rows, columns, and queries.
Clause order and the shape of a SELECT query.
Sort before you limit, or top-N is arbitrary.
WHERE is evaluated before SELECT aliases exist.
Learn the basic shape of relational data.
Comparisons, AND/OR, IN, BETWEEN, and LIKE.