Skip to content
Cheatsheets/SQL Query Basics Cheatsheet
Cheatsheet

SQL Query Basics Cheatsheet

SELECT, WHERE, ORDER BY, and LIMIT at a glance.

The skeleton

A whole query
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

Clause run order

You write SELECT first, but the database runs the clauses in a different order. That is why a SELECT alias cannot be used inWHERE, but can in ORDER BY.

WrittenActually runs
SELECT5
FROM1
WHERE2
GROUP BY3
HAVING4
ORDER BY6
LIMIT7

Choosing columns

GoalSQL
Every columnselect *
Specific columnsselect name, price
Rename a columnselect price as cost
Computed columnselect price * 1.06 as with_tax
Drop duplicatesselect distinct city

Filtering with WHERE

OperatorMatches
=   <>Equal / not equal
<<=>>=Comparisons (numbers, dates, text)
between a and bInclusive range
in (1, 2, 3)Any value in a list
like 'a%'Pattern: % = any run, _ = one char
is null / is not nullMissing / present
and or notCombine conditions (use parentheses)

Sorting & limiting

Top 5, newest first
order by order_date desc, order_id   -- tiebreak keeps it stable
limit 5
Watch out

= never matches NULL, even null = nullis unknown. Use is null, or is distinct from for a null-safe "not equal".