Quick reference · SQL

SQL cheat sheet: essential syntax with examples

The syntax people look up most, grouped by task, each with an example you can run in the SQL editor on the StoreSQL database.

Updated: October 18, 2026Printable: press Ctrl+P and save as PDF
In this guide

How to use this guide

This SQL cheat sheet brings together the syntax you use every day: reading and filtering data, summarising it, joining tables, writing subqueries and changing the structure. Each row shows what the statement is for, its general form and a runnable example on the fictional StoreSQL (customers, products, orders, order_items, categories, employees and payments).

The examples were run in SQLite. Most work the same way in PostgreSQL, MySQL, SQL Server and Oracle; the last section sums up the most common differences. If you are just starting out, the cheat sheet does not replace the SQL course: it is there to remind you of a statement's form once you already understand what it does.

Query and filter data

For…SyntaxExample in StoreSQL
Choose columnsSELECT col1, col2 FROM table_name;SELECT name, city FROM customers;
All columnsSELECT * FROM table_name;SELECT * FROM products;
Give an aliasSELECT col AS alias FROM table_name;SELECT price * stock AS stock_value FROM products;
Remove duplicatesSELECT DISTINCT col FROM table_name;SELECT DISTINCT city FROM customers;
Filter rowsWHERE condiciónSELECT name FROM customers WHERE city = 'London' AND active = 1;
Range of valuescol BETWEEN a AND bSELECT name, price FROM products WHERE price BETWEEN 20 AND 100;
List of valuescol IN (a, b, c)SELECT name FROM customers WHERE city IN ('Bristol', 'Leeds');
Text patterncol LIKE 'pattern'SELECT name FROM products WHERE name LIKE 'Monitor%';
Missing valuescol IS NULL / IS NOT NULLSELECT name FROM customers WHERE email IS NULL;
Tidy upORDER BY col [ASC|DESC]SELECT name, price FROM products ORDER BY price DESC, name;
Limit rowsLIMIT n [OFFSET m]SELECT name, price FROM products ORDER BY price DESC LIMIT 3;
Conditional valueCASE WHEN … THEN … ELSE … ENDSELECT name, CASE WHEN stock = 0 THEN 'out_of_stock' ELSE 'available' END AS situation FROM products;
Replace NULLCOALESCE(col, value)SELECT name, COALESCE(email, 'no email') AS email FROM customers;

Summarise and group data

For…SyntaxExample in StoreSQL
Count rowsCOUNT(*)SELECT COUNT(*) AS orders FROM orders;
Count values that are presentCOUNT(col) ignores NULLsSELECT COUNT(email) AS with_email FROM customers;
Add up and averageSUM(col), AVG(col)SELECT SUM(total) AS amount, ROUND(AVG(total), 2) AS average_ticket FROM orders;
Minimum and maximumMIN(col), MAX(col)SELECT MIN(date) AS first, MAX(date) AS last FROM orders;
Summarise by groupGROUP BY colSELECT status, COUNT(*) AS orders FROM orders GROUP BY status;
Filter groupsHAVING condición_agregadaSELECT city, COUNT(*) AS customers FROM customers GROUP BY city HAVING COUNT(*) >= 3;
Count distinctCOUNT(DISTINCT col)SELECT COUNT(DISTINCT customer_id) AS customers_with_orders FROM orders;

Combine tables with JOIN

For…SyntaxExample in StoreSQL
Matches onlytable_a JOIN table_b ON a.col = b.colSELECT c.name, p.total FROM customers c JOIN orders p ON p.customer_id = c.id;
Keep every row on the leftLEFT JOIN … ON …SELECT c.name, p.id AS order_record FROM customers c LEFT JOIN orders p ON p.customer_id = c.id;
Rows with no matchLEFT JOIN … WHERE b.id IS NULLSELECT c.name FROM customers c LEFT JOIN orders p ON p.customer_id = c.id WHERE p.id IS NULL;
Join three tablesJOIN … JOIN …SELECT p.id, pr.name, d.quantity FROM orders p JOIN order_items d ON d.order_id = p.id JOIN products pr ON pr.id = d.product_id;
A table joined to itselftable_name a JOIN table_name b ON b.id = a.refSELECT e.name AS employee, r.name AS owner FROM employees e LEFT JOIN employees r ON r.id = e.manager_id;
Stack resultsconsulta1 UNION [ALL] consulta2SELECT name FROM customers WHERE city = 'London' UNION SELECT name FROM customers WHERE active = 0;

Subqueries, CTEs and window functions

For…SyntaxExample in StoreSQL
Subquery as valueWHERE col > (SELECT …)SELECT id, total FROM orders WHERE total > (SELECT AVG(total) FROM orders);
ExistenceWHERE EXISTS (SELECT 1 …)SELECT c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders p WHERE p.customer_id = c.id);
Named query (CTE)WITH name AS (SELECT …) SELECT … FROM nameWITH by_customer AS (SELECT customer_id, SUM(total) AS amount FROM orders GROUP BY customer_id) SELECT customer_id, amount FROM by_customer WHERE amount > 200;
Number rowsROW_NUMBER() OVER (ORDER BY col)SELECT name, price, ROW_NUMBER() OVER (ORDER BY price DESC) AS position FROM products;
Number per group… OVER (PARTITION BY g ORDER BY col)SELECT category, name, RANK() OVER (PARTITION BY category ORDER BY price DESC) AS position FROM products;
Running totalSUM(col) OVER (ORDER BY col2)SELECT date, total, SUM(total) OVER (ORDER BY date, id) AS cumulative FROM orders;

Insert, update and delete data

For…SyntaxExample in StoreSQL
Insert a rowINSERT INTO t (cols) VALUES (values);INSERT INTO categories (id, name) VALUES (6, 'Networks');
Insert from a queryINSERT INTO t (cols) SELECT …;INSERT INTO categories (id, name) SELECT 7, 'Printing';
Update rowsUPDATE t SET col = value WHERE …;UPDATE products SET stock = stock + 10 WHERE name = 'Keyboard';
Delete rowsDELETE FROM t WHERE …;DELETE FROM orders WHERE status = 'cancelled' AND id NOT IN (SELECT order_id FROM order_items);
Group changes togetherBEGIN; …; COMMIT; or ROLLBACK;BEGIN; UPDATE products SET stock = 0 WHERE id = 4; ROLLBACK;

Create and change tables

For…SyntaxExample in StoreSQL
Create a tableCREATE TABLE t (col type constraints);CREATE TABLE labels (id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE);
Foreign keyFOREIGN KEY (col) REFERENCES other(id)CREATE TABLE reviews (id INTEGER PRIMARY KEY, product_id INTEGER NOT NULL, text_value TEXT, FOREIGN KEY (product_id) REFERENCES products(id));
Add a columnALTER TABLE t ADD COLUMN col type;ALTER TABLE customers ADD COLUMN phone TEXT;
Create an indexCREATE INDEX name ON t (col);CREATE INDEX idx_orders_customer ON orders (customer_id);
Creating a viewCREATE VIEW v AS SELECT …;CREATE VIEW shipped_orders AS SELECT id, customer_id, total FROM orders WHERE status = 'shipped';
Drop a tableDROP TABLE t;CREATE TABLE temporary (id INTEGER); DROP TABLE temporary;

Common differences between engines

These are the differences that most often break a query when changing databases. Always check the documentation for the version you use.

TaskPostgreSQLMySQLSQL ServerOracleSQLite
Limit rowsLIMIT nLIMIT nTOP n or OFFSET … FETCHFETCH FIRST n ROWS ONLYLIMIT n
Concatenate text|| or CONCAT()CONCAT()+ or CONCAT()||||
Current dateCURRENT_DATECURDATE()CAST(GETDATE() AS date)SYSDATE or CURRENT_DATEdate('now')
Auto-generated keyGENERATED … AS IDENTITYAUTO_INCREMENTIDENTITY(1,1)GENERATED … AS IDENTITYINTEGER PRIMARY KEY
Empty string and NULLThey are differentThey are differentThey are differentAn empty string is NULLThey are different

Where to go next

If a row in the cheat sheet is not clear to you, open the corresponding lesson: SELECT and FROM, WHERE, GROUP BY, INNER JOIN, CTE or window functions. To look up a specific question, use the SQL glossary, and for practice, the JOIN and aggregate exercises.