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_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164

Query: get columns

Every query starts with SELECT and FROM. List the columns you want after SELECT, separated by commas.

CommandWhat it doesExampleLesson
SELECT … FROMpick columns from a tableSELECT name, price FROM productsSELECT: query columns
SELECT *return every columnSELECT * FROM customersBasics: tables, rows, columns
DISTINCTshow each value onceSELECT DISTINCT city FROM customersDISTINCT: drop duplicates
+ - * /calculate with columnsSELECT name, price * 0.9 FROM productsCalculations and column aliases
ASname a column in the resultSELECT ROUND(price * 0.9, 2) AS sale_price FROM productsCalculations 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_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-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.

CommandWhat it doesExampleLesson
WHEREkeep only rows that meet a conditionSELECT name FROM customers WHERE city = 'Boston'WHERE: filter rows
= <> < > <= >=compare valuesWHERE price <= 4.99WHERE: filter rows
AND, OR, NOTcombine conditionsWHERE country = 'UK' AND segment = 'Business'AND, OR, NOT
INmatch any value in a listWHERE category IN ('Paper', 'Filing')IN and BETWEEN
BETWEEN … ANDa range, both ends includedWHERE order_date BETWEEN '2026-03-01' AND '2026-03-31'IN and BETWEEN
LIKEpattern match: % for any run of characters, _ for exactly oneWHERE name LIKE '%Ltd'LIKE: pattern matching
IS NULL, IS NOT NULLfind empty fieldsWHERE phone IS NULLNULL and COALESCE
COALESCEfallback value for an empty fieldSELECT name, COALESCE(phone, 'not given') FROM customersNULL 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.

CommandWhat it doesExampleLesson
ORDER BY … ASC / DESCsort, lowest first or highest firstSELECT name, price FROM products ORDER BY price DESCORDER BY and LIMIT
LIMIT, OFFSETreturn only the first rowsSELECT order_id, order_date FROM orders ORDER BY order_date DESC LIMIT 3ORDER 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_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

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.

CommandWhat it doesExampleLesson
COUNTcount rowsSELECT COUNT(*) FROM ordersCOUNT: count rows
SUM, AVG, MIN, MAXtotal, average, smallest and largest valueSELECT AVG(salary), MAX(salary) FROM employeesSUM, AVG, MIN, MAX
GROUP BYone result per groupSELECT department, COUNT(*) FROM employees GROUP BY departmentGROUP BY: summarize groups
HAVINGfilter groupsSELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) >= 2HAVING: filter groups
CASE WHEN … THEN … ENDif/then logic, like IF in ExcelSELECT name, CASE WHEN price >= 100 THEN 'premium' ELSE 'budget' END AS tier FROM productsCASE WHEN: conditional logic
UPPER, LOWER, LENGTH, SUBSTR, ||change, cut and join textSELECT first_name || ' ' || last_name AS full_name FROM employeesString functions
date, strftimework with dates, pull out the month or yearSELECT order_id, strftime('%m', order_date) AS month FROM ordersDates 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.

CommandWhat it doesExampleLesson
JOIN … ONcombine tables, matching rows onlySELECT o.order_id, c.name FROM orders o JOIN customers c ON c.customer_id = o.customer_idINNER JOIN: joining tables
LEFT JOINevery row on the left, even without a matchSELECT e.last_name, o.order_id FROM employees e LEFT JOIN orders o ON o.employee_id = e.employee_idLEFT JOIN
several JOINsthree or more tablesSELECT 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_idJoining multiple tables
self joinjoin a table to itselfSELECT e.last_name, m.last_name AS manager FROM employees e LEFT JOIN employees m ON m.employee_id = e.manager_idSelf join
UNION, UNION ALLstack results on top of each otherSELECT name FROM customers UNION ALL SELECT first_name || ' ' || last_name FROM employeesUNION
subquerya query inside a querySELECT name, price FROM products WHERE price > (SELECT AVG(price) FROM products)Subqueries
EXISTS, NOT EXISTSis 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.

CommandWhat it doesExampleLesson
WITHname 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 > 500WITH (CTE)
ROW_NUMBER, RANK … OVERrank or number rowsSELECT last_name, salary, RANK() OVER (ORDER BY salary DESC) AS salary_rank FROM employeesWindow functions: ROW_NUMBER, RANK
SUM() OVER (PARTITION BY …)group total next to every row, running totalsSELECT last_name, department, salary, SUM(salary) OVER (PARTITION BY department) AS dept_total FROM employeesRunning totals and shares
LAG, LEADvalue from the previous or next rowSELECT order_id, order_date, LAG(order_date) OVER (ORDER BY order_date) AS previous FROM ordersLAG and LEAD
SUM(CASE WHEN …)pivot: turn values into columnsSELECT strftime('%m', order_date) AS month, SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled FROM orders GROUP BY monthPivot with CASE WHEN
GROUP BY … HAVING COUNT(*) > 1find duplicatesSELECT city, COUNT(*) FROM customers GROUP BY city HAVING COUNT(*) > 1Finding 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.

CommandWhat it doesExampleLesson
INSERT INTO … VALUESadd a rowINSERT INTO products (product_id, name, category, price, stock) VALUES (13, 'Hole punch', 'Filing', 7.99, 50)INSERT: adding rows
UPDATE … SET … WHEREchange valuesUPDATE products SET price = 5.29 WHERE product_id = 1UPDATE: changing rows
DELETE FROM … WHEREremove rowsDELETE FROM products WHERE product_id = 13DELETE: removing rows
BEGIN, COMMIT, ROLLBACKseveral changes as all or nothingBEGIN; 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.

CommandWhat it doesExampleLesson
CREATE TABLEcreate a new tableCREATE TABLE suppliers (supplier_id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT)CREATE TABLE
ALTER TABLE … ADD COLUMNadd a columnALTER TABLE customers ADD COLUMN email TEXTALTER TABLE
PRIMARY KEY, REFERENCESprimary and foreign keysCREATE TABLE invoices (invoice_id INTEGER PRIMARY KEY, order_id INTEGER REFERENCES orders(order_id))Primary and foreign keys
CREATE VIEWa saved query you can use like a tableCREATE VIEW open_orders AS SELECT * FROM orders WHERE status = 'open'Views
DROP TABLEdelete a table and everything in itDROP 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:

TaskMySQLPostgreSQLSQL ServerSQLite (these exercises)
first 3 rowsLIMIT 3LIMIT 3 or FETCH FIRST 3 ROWS ONLYSELECT TOP (3) …LIMIT 3
fallback for NULLCOALESCE or IFNULLCOALESCECOALESCE or ISNULLCOALESCE or IFNULL
join textCONCAT(a, b); without the PIPES_AS_CONCAT mode, || means ORa || b or concat(a, b)a + b or CONCAT(a, b)a || b
today's dateCURDATE() or CURRENT_DATECURRENT_DATECAST(GETDATE() AS date); from SQL Server 2025 also CURRENT_DATEdate('now') (UTC), local time with date('now', 'localtime')
FULL OUTER JOINnot available, only LEFT and RIGHT JOINyesyesyes, since version 3.39.0
auto-numbered IDid INT AUTO_INCREMENTid bigint GENERATED ALWAYS AS IDENTITYid 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.

Next: learn SQL step by step

A cheat sheet is great for looking things up; practice is what makes it stick. The course starts with tables, rows and columns and takes you lesson by lesson to joins and reports. Level 1 is free.

Start lesson 1

Write to us

Choose language

Select your preferred language