RUNWEBTOOLS
English

SQL Cheat Sheet: The Statements You Use Every Day

The core SQL statements for querying and changing data, grouped by task. The exact syntax varies slightly between databases (PostgreSQL, MySQL, SQLite, SQL Server), but the fundamentals below are near-universal. To tidy a messy query, use the SQL formatter.

Updated 2026-07-06

Querying (SELECT)

StatementWhat it does
SELECT * FROM tReturn every column and row from table t
SELECT a, b FROM tReturn only columns a and b
SELECT DISTINCT a FROM tReturn unique values of a
... WHERE a = 5Filter rows where a equals 5
... ORDER BY a DESCSort by a, descending
... LIMIT 10Return at most 10 rows
... OFFSET 20Skip the first 20 rows (paging)
SELECT COUNT(*) FROM tCount rows
SELECT SUM(a), AVG(a) FROM tAggregate: total and average of a
... GROUP BY categoryGroup rows to aggregate per category
... HAVING COUNT(*) > 5Filter groups (WHERE for aggregates)

Filtering (WHERE)

StatementWhat it does
WHERE a IN (1, 2, 3)Match any value in a list
WHERE a BETWEEN 1 AND 9Match a range (inclusive)
WHERE name LIKE 'A%'Pattern match: starts with A (% = any chars)
WHERE name LIKE '_at'_ matches exactly one character
WHERE a IS NULLMatch rows where a has no value
WHERE a > 5 AND b < 10Combine conditions with AND / OR

Joining tables

StatementWhat it does
INNER JOIN u ON t.id = u.tidRows with a match in both tables
LEFT JOIN u ON t.id = u.tidAll rows from the left table, matched or not
RIGHT JOIN u ON t.id = u.tidAll rows from the right table
FULL JOIN u ON t.id = u.tidAll rows from both tables

Changing data

StatementWhat it does
INSERT INTO t (a, b) VALUES (1, 2)Add a new row
UPDATE t SET a = 5 WHERE id = 1Change existing rows (mind the WHERE!)
DELETE FROM t WHERE id = 1Remove rows (mind the WHERE!)

Schema (tables & indexes)

StatementWhat it does
CREATE TABLE t (id INT, name TEXT)Create a new table
ALTER TABLE t ADD col TEXTAdd a column
DROP TABLE tDelete a table and all its data
CREATE INDEX idx ON t (a)Add an index to speed up lookups on a

A safety habit worth keeping: always write the WHERE clause of an UPDATE or DELETE first. Running one without a WHERE changes or deletes every row in the table.

Related tools