SQL commands cheat sheet: every command with an example
Every command and clause from our SQL course in one place, grouped by job. Each row tells you what the command is for, shows a short query on our practice database and links to the lesson where you practice it.
In short: six commands cover most everyday queries. SELECT picks the columns, FROM names the table, WHERE filters rows, GROUP BY summarizes, ORDER BY sorts and JOIN combines tables. To change data you add INSERT, UPDATE and DELETE.
Jump to: Query, Filter, Sort, Analyze, Join, Advanced, Modify data, Tables, Cheat sheet, Database differences.
Try one right now
A list of commands only sticks once you type them. The practice database belongs to a small online office supply store with customers mostly in the US and the UK and five tables: customers, products, employees, orders and order_items. Every example on this page runs on that data.
Task Sales is planning visits in Boston. From the customers table, show the columns name and phone, but only for customers whose city is Boston.
customers 12 rows, 7 columns
| customer_id | name | city | country | customer_since | segment | phone |
|---|---|---|---|---|---|---|
| 1 | Harbor Fremont Partners | Boston | USA | 2021-03-15 | Business | 617-555-0142 |
| 2 | Emily Carter | Chicago | USA | 2022-07-01 | Consumer | NULL |
| 3 | Riverside County Office | Riverside | USA | 2020-11-20 | Government | 951-555-0110 |
| 4 | Raj Patel | Leeds | UK | 2023-01-09 | Consumer | 0113 496 0123 |
| 5 | Lakeview Hotel Ltd | Manchester | UK | 2022-04-18 | Business | 0161 496 0456 |
| 6 | Olivia Brooks | Austin | USA | 2024-02-27 | Consumer | NULL |
| 7 | Greene & Shaw LLP | London | UK | 2021-09-05 | Business | 020 7946 0321 |
| 8 | Maple Grove High School | Austin | USA | 2023-08-14 | School | 512-555-0187 |
| 9 | Chloe Evans | Boston | USA | 2025-05-30 | Consumer | 617-555-0199 |
| 10 | Northline Printing Co | Toronto | Canada | 2020-06-12 | Business | 416-555-0133 |
| 11 | Daniel Kim | Seattle | USA | 2024-10-03 | Consumer | NULL |
| 12 | Westbrook Dental Clinic | Chicago | USA | 2022-12-01 | Business | 312-555-0164 |
Query: get columns
Every query starts with SELECT and FROM. List the columns you want after SELECT, separated by commas.
| Command | What it does | Example | Lesson |
|---|---|---|---|
SELECT … FROM | pick columns from a table | SELECT name, price FROM products | SELECT: query columns |
SELECT * | return every column | SELECT * FROM customers | Basics: tables, rows, columns |
DISTINCT | show each value once | SELECT DISTINCT city FROM customers | DISTINCT: drop duplicates |
+ - * / | calculate with columns | SELECT name, price * 0.9 FROM products | Calculations and column aliases |
AS | name a column in the result | SELECT ROUND(price * 0.9, 2) AS sale_price FROM products | Calculations and column aliases |
Quick practice: which cities does the store have customers in? One extra keyword does it.
Task Marketing is planning a mailing per city and wants to know which cities the shop has customers in at all. From the customers table, get the city column, each city only once.
customers 12 rows, 7 columns
| customer_id | name | city | country | customer_since | segment | phone |
|---|---|---|---|---|---|---|
| 1 | Harbor Fremont Partners | Boston | USA | 2021-03-15 | Business | 617-555-0142 |
| 2 | Emily Carter | Chicago | USA | 2022-07-01 | Consumer | NULL |
| 3 | Riverside County Office | Riverside | USA | 2020-11-20 | Government | 951-555-0110 |
| 4 | Raj Patel | Leeds | UK | 2023-01-09 | Consumer | 0113 496 0123 |
| 5 | Lakeview Hotel Ltd | Manchester | UK | 2022-04-18 | Business | 0161 496 0456 |
| 6 | Olivia Brooks | Austin | USA | 2024-02-27 | Consumer | NULL |
| 7 | Greene & Shaw LLP | London | UK | 2021-09-05 | Business | 020 7946 0321 |
| 8 | Maple Grove High School | Austin | USA | 2023-08-14 | School | 512-555-0187 |
| 9 | Chloe Evans | Boston | USA | 2025-05-30 | Consumer | 617-555-0199 |
| 10 | Northline Printing Co | Toronto | Canada | 2020-06-12 | Business | 416-555-0133 |
| 11 | Daniel Kim | Seattle | USA | 2024-10-03 | Consumer | NULL |
| 12 | Westbrook Dental Clinic | Chicago | USA | 2022-12-01 | Business | 312-555-0164 |
Filter: only the rows you need
WHERE always comes after FROM. Put text in single quotes, write decimals with a period and dates as text in the form YYYY-MM-DD.
| Command | What it does | Example | Lesson |
|---|---|---|---|
WHERE | keep only rows that meet a condition | SELECT name FROM customers WHERE city = 'Boston' | WHERE: filter rows |
= <> < > <= >= | compare values | WHERE price <= 4.99 | WHERE: filter rows |
AND, OR, NOT | combine conditions | WHERE country = 'UK' AND segment = 'Business' | AND, OR, NOT |
IN | match any value in a list | WHERE category IN ('Paper', 'Filing') | IN and BETWEEN |
BETWEEN … AND | a range, both ends included | WHERE order_date BETWEEN '2026-03-01' AND '2026-03-31' | IN and BETWEEN |
LIKE | pattern match: % for any run of characters, _ for exactly one | WHERE name LIKE '%Ltd' | LIKE: pattern matching |
IS NULL, IS NOT NULL | find empty fields | WHERE phone IS NULL | NULL and COALESCE |
COALESCE | fallback value for an empty field | SELECT name, COALESCE(phone, 'not given') FROM customers | NULL and COALESCE |
Sort and limit
ORDER BY goes near the end of the query and LIMIT comes last. Without ORDER BY, the database is free to return rows in any order.
| Command | What it does | Example | Lesson |
|---|---|---|---|
ORDER BY … ASC / DESC | sort, lowest first or highest first | SELECT name, price FROM products ORDER BY price DESC | ORDER BY and LIMIT |
LIMIT, OFFSET | return only the first rows | SELECT order_id, order_date FROM orders ORDER BY order_date DESC LIMIT 3 | ORDER BY and LIMIT |
The three most recent orders for a dashboard: ORDER BY and LIMIT working together.
Task The dashboard should show the three most recent orders. Show order_id, order_date and status for those three orders, newest first.
orders 18 rows, 5 columns
| order_id | customer_id | order_date | status | employee_id |
|---|---|---|---|---|
| 1001 | 1 | 2026-01-08 | delivered | 3 |
| 1002 | 4 | 2026-01-12 | delivered | 4 |
| 1003 | 3 | 2026-01-20 | delivered | 3 |
| 1004 | 7 | 2026-02-03 | delivered | 4 |
| 1005 | 2 | 2026-02-11 | cancelled | 8 |
| 1006 | 1 | 2026-02-25 | delivered | 3 |
| 1007 | 10 | 2026-03-04 | delivered | 2 |
| 1008 | 5 | 2026-03-17 | delivered | 4 |
| 1009 | 8 | 2026-03-30 | delivered | 3 |
| 1010 | 6 | 2026-04-07 | delivered | 8 |
| 1011 | 12 | 2026-04-22 | delivered | 4 |
| 1012 | 3 | 2026-05-06 | delivered | 3 |
| 1013 | 9 | 2026-05-19 | cancelled | 8 |
| 1014 | 7 | 2026-06-02 | shipped | 4 |
| 1015 | 1 | 2026-06-10 | shipped | 3 |
| 1016 | 11 | 2026-06-12 | open | NULL |
| 1017 | 4 | 2026-06-13 | open | NULL |
| 1018 | 10 | 2026-06-14 | open | NULL |
Analyze: count, total, group
These commands turn a long list into a report, much like a PivotTable in Excel. WHERE filters rows before grouping; HAVING filters the finished groups.
| Command | What it does | Example | Lesson |
|---|---|---|---|
COUNT | count rows | SELECT COUNT(*) FROM orders | COUNT: count rows |
SUM, AVG, MIN, MAX | total, average, smallest and largest value | SELECT AVG(salary), MAX(salary) FROM employees | SUM, AVG, MIN, MAX |
GROUP BY | one result per group | SELECT department, COUNT(*) FROM employees GROUP BY department | GROUP BY: summarize groups |
HAVING | filter groups | SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) >= 2 | HAVING: filter groups |
CASE WHEN … THEN … END | if/then logic, like IF in Excel | SELECT name, CASE WHEN price >= 100 THEN 'premium' ELSE 'budget' END AS tier FROM products | CASE WHEN: conditional logic |
UPPER, LOWER, LENGTH, SUBSTR, || | change, cut and join text | SELECT first_name || ' ' || last_name AS full_name FROM employees | String functions |
date, strftime | work with dates, pull out the month or year | SELECT order_id, strftime('%m', order_date) AS month FROM orders | Dates and times |
Join: several tables
A database keeps customers, orders and products in separate tables. JOIN brings them together through a shared column, usually an ID. The short names after each table (o, c) are aliases and save typing.
| Command | What it does | Example | Lesson |
|---|---|---|---|
JOIN … ON | combine tables, matching rows only | SELECT o.order_id, c.name FROM orders o JOIN customers c ON c.customer_id = o.customer_id | INNER JOIN: joining tables |
LEFT JOIN | every row on the left, even without a match | SELECT e.last_name, o.order_id FROM employees e LEFT JOIN orders o ON o.employee_id = e.employee_id | LEFT JOIN |
several JOINs | three or more tables | SELECT o.order_id, p.name, i.quantity FROM orders o JOIN order_items i ON i.order_id = o.order_id JOIN products p ON p.product_id = i.product_id | Joining multiple tables |
self join | join a table to itself | SELECT e.last_name, m.last_name AS manager FROM employees e LEFT JOIN employees m ON m.employee_id = e.manager_id | Self join |
UNION, UNION ALL | stack results on top of each other | SELECT name FROM customers UNION ALL SELECT first_name || ' ' || last_name FROM employees | UNION |
subquery | a query inside a query | SELECT name, price FROM products WHERE price > (SELECT AVG(price) FROM products) | Subqueries |
EXISTS, NOT EXISTS | is there a matching row in another table? | SELECT last_name FROM employees e WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.employee_id = e.employee_id) | EXISTS and NOT EXISTS |
Advanced
Window functions calculate across rows without collapsing them: every row stays in the result and gets, for example, its rank or its group total added.
| Command | What it does | Example | Lesson |
|---|---|---|---|
WITH | name an intermediate result (CTE) | WITH totals AS (SELECT order_id, SUM(quantity * unit_price) AS total FROM order_items GROUP BY order_id) SELECT * FROM totals WHERE total > 500 | WITH (CTE) |
ROW_NUMBER, RANK … OVER | rank or number rows | SELECT last_name, salary, RANK() OVER (ORDER BY salary DESC) AS salary_rank FROM employees | Window functions: ROW_NUMBER, RANK |
SUM() OVER (PARTITION BY …) | group total next to every row, running totals | SELECT last_name, department, salary, SUM(salary) OVER (PARTITION BY department) AS dept_total FROM employees | Running totals and shares |
LAG, LEAD | value from the previous or next row | SELECT order_id, order_date, LAG(order_date) OVER (ORDER BY order_date) AS previous FROM orders | LAG and LEAD |
SUM(CASE WHEN …) | pivot: turn values into columns | SELECT strftime('%m', order_date) AS month, SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled FROM orders GROUP BY month | Pivot with CASE WHEN |
GROUP BY … HAVING COUNT(*) > 1 | find duplicates | SELECT city, COUNT(*) FROM customers GROUP BY city HAVING COUNT(*) > 1 | Finding duplicates |
Modify data
These commands change what is stored in a table. With UPDATE and DELETE, leaving out WHERE hits every row in the table, so run the condition as a SELECT first.
| Command | What it does | Example | Lesson |
|---|---|---|---|
INSERT INTO … VALUES | add a row | INSERT INTO products (product_id, name, category, price, stock) VALUES (13, 'Hole punch', 'Filing', 7.99, 50) | INSERT: adding rows |
UPDATE … SET … WHERE | change values | UPDATE products SET price = 5.29 WHERE product_id = 1 | UPDATE: changing rows |
DELETE FROM … WHERE | remove rows | DELETE FROM products WHERE product_id = 13 | DELETE: removing rows |
BEGIN, COMMIT, ROLLBACK | several changes as all or nothing | BEGIN; UPDATE products SET stock = stock - 5 WHERE product_id = 1; COMMIT; | Transactions |
Create and change tables
These commands build the structure: tables, columns, keys and views. The practice database keeps data types simple (INTEGER, REAL, TEXT); other databases offer more, such as VARCHAR, DECIMAL or DATE.
| Command | What it does | Example | Lesson |
|---|---|---|---|
CREATE TABLE | create a new table | CREATE TABLE suppliers (supplier_id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT) | CREATE TABLE |
ALTER TABLE … ADD COLUMN | add a column | ALTER TABLE customers ADD COLUMN email TEXT | ALTER TABLE |
PRIMARY KEY, REFERENCES | primary and foreign keys | CREATE TABLE invoices (invoice_id INTEGER PRIMARY KEY, order_id INTEGER REFERENCES orders(order_id)) | Primary and foreign keys |
CREATE VIEW | a saved query you can use like a table | CREATE VIEW open_orders AS SELECT * FROM orders WHERE status = 'open' | Views |
DROP TABLE | delete a table and everything in it | DROP TABLE suppliers |
Cheat sheet: the order of clauses
The clauses of a query always appear in this order. Skip the ones you don't need; the rest keep their places.
SELECT DISTINCT column, EXPRESSION AS name, COUNT(*)
FROM table_name t
JOIN other_table o ON o.id = t.other_id
WHERE condition
GROUP BY column
HAVING COUNT(*) > 1
ORDER BY column DESC
LIMIT 10;
And the commands for changing data and structure:
INSERT INTO table_name (column1, column2) VALUES (1, 'text');
UPDATE table_name SET column1 = 2 WHERE id = 1;
DELETE FROM table_name WHERE id = 1;
CREATE TABLE table_name (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
ALTER TABLE table_name ADD COLUMN email TEXT;
Five rules that prevent most mistakes:
- Text goes in single quotes:
'Boston', not"Boston". - Decimals use a period:
4.99. - Find empty fields with
IS NULL, never= NULL. - WHERE filters rows before grouping, HAVING after.
- Never run UPDATE or DELETE without WHERE.
To print it, print this page (Ctrl+P, or Cmd+P on a Mac). The site header and footer are left out; if you only want the cheat sheet, pick the pages it is on in the print dialog.
Where MySQL, PostgreSQL, SQL Server and SQLite differ
The commands above are standard SQL and work almost everywhere. Our exercises run on SQLite. In these spots, other databases want something different:
| Task | MySQL | PostgreSQL | SQL Server | SQLite (these exercises) |
|---|---|---|---|---|
| first 3 rows | LIMIT 3 | LIMIT 3 or FETCH FIRST 3 ROWS ONLY | SELECT TOP (3) … | LIMIT 3 |
| fallback for NULL | COALESCE or IFNULL | COALESCE | COALESCE or ISNULL | COALESCE or IFNULL |
| join text | CONCAT(a, b); without the PIPES_AS_CONCAT mode, || means OR | a || b or concat(a, b) | a + b or CONCAT(a, b) | a || b |
| today's date | CURDATE() or CURRENT_DATE | CURRENT_DATE | CAST(GETDATE() AS date); from SQL Server 2025 also CURRENT_DATE | date('now') (UTC), local time with date('now', 'localtime') |
| FULL OUTER JOIN | not available, only LEFT and RIGHT JOIN | yes | yes | yes, since version 3.39.0 |
| auto-numbered ID | id INT AUTO_INCREMENT | id bigint GENERATED ALWAYS AS IDENTITY | id INT IDENTITY(1, 1) | id INTEGER PRIMARY KEY |
Watch out for empty fields when joining text: CONCAT skips NULL in PostgreSQL and SQL Server, but in MySQL one NULL makes the whole result NULL. With + in SQL Server, the default setting also gives NULL. For more differences, see MySQL vs PostgreSQL vs SQL Server.
Sources: MySQL Reference Manual (String Functions, Server SQL Modes, JOIN Clause, Date and Time Functions, Using AUTO_INCREMENT), PostgreSQL documentation (String Functions, Date/Time Functions, Table Expressions, Identity Columns), Microsoft Learn (String Concatenation, CONCAT, CURRENT_DATE, FROM clause, IDENTITY), sqlite.org (SQL Language Expressions, Date and Time Functions, Release 3.39.0, Autoincrement); LIMIT/TOP and NULL as documented in our ORDER BY and NULL lessons.
Frequently asked questions
Which SQL commands should I learn first?
SELECT, FROM, WHERE and ORDER BY. With those four you can pull exactly the data you need from one table, which is most of what office work asks for. Next come GROUP BY for reports and JOIN for several tables. The course follows that order and starts with the basics.
What are DDL, DML and DCL?
Labels that are often used to group SQL commands. DDL (Data Definition Language) defines structure: CREATE, ALTER, DROP. DML (Data Manipulation Language) changes content: INSERT, UPDATE, DELETE; depending on the textbook, SELECT belongs here or gets its own label, DQL (Data Query Language). DCL handles permissions with GRANT and REVOKE, and COMMIT and ROLLBACK are sometimes called TCL. In practice, knowing the commands matters more than the labels.
Do SQL commands have to be uppercase?
No. select and SELECT mean the same to the database. Uppercase keywords with lowercase column names are simply the common style because the query is easier to scan. Values inside quotes are a different story: there, case can matter.
In what order does the database run a query?
Not in the order you write it: FROM and JOIN come first, then WHERE, GROUP BY and HAVING, then SELECT, and finally ORDER BY and LIMIT. That is why MySQL, PostgreSQL and SQL Server reject a column alias from AS inside WHERE. The full story is in SQL order of execution.
Can I practice these commands?
Yes. Every lesson in the Lesson column has several exercises on the same database, with hints and a check of your query. For mixed exercises, see SQL practice.