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 manyClause 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.
| Written | Actually runs |
|---|---|
| SELECT | 5 |
| FROM | 1 |
| WHERE | 2 |
| GROUP BY | 3 |
| HAVING | 4 |
| ORDER BY | 6 |
| LIMIT | 7 |
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
Top 5, newest first
order by order_date desc, order_id -- tiebreak keeps it stable
limit 5Watch out
= never matches NULL, even null = nullis unknown. Use is null, or is distinct from for a null-safe "not equal".
Related
Lesson
What Is SQL?
Understand tables, rows, columns, and queries.
Lesson
Tables, Rows, and Columns in SQL
Learn the basic shape of relational data.
Lesson
Meet the SQL Workbench
Run queries and read results in the browser.
Lesson
Your First SQL SELECT Statement
Write a first SELECT and read the returned rows.