SQLSQL

SQL cheatsheet – syntax overview

63 key commands and patterns for quick reference.

SELECT basics Filtering (WHERE) Sorting & Limiting Aggregation Joins Subqueries & Sets Modifying data (DML) Schema (DDL) & Constraints CTE & Window functions Transactions, Indexes & Dialects

SELECT basics

SELECT spalte1, spalte2 FROM tabelle;Query specific columns
SELECT * FROM tabelle;All columns (for exploring only)
SELECT DISTINCT spalte FROM t;Remove duplicates
SELECT preis * 1.19 AS brutto FROM t;Computed column with an alias
SELECT 'a' || 'b';Concatenate text (MySQL: CONCAT)
SELECT COUNT(*) FROM t;Count rows

Filtering (WHERE)

WHERE a = 1 AND b <> 2Comparison and combination
WHERE a IN (1, 2, 3)Value in a list
WHERE a BETWEEN 5 AND 10Range including bounds
WHERE name LIKE 'A%'Pattern: % any number of characters, _ exactly one character
WHERE spalte IS NULLCheck for NULL (never = NULL)
WHERE NOT (a = 1 OR b = 2)Negation, use parentheses
WHERE name ILIKE '%tex%'Case-insensitive LIKE (PostgreSQL)

Sorting & Limiting

ORDER BY preis DESC, name ASCMulti-level sorting
LIMIT 10The first 10 rows
LIMIT 10 OFFSET 20Page 3 at 10 per page
FETCH FIRST 10 ROWS ONLYStandard SQL variant of LIMIT
ORDER BY a NULLS LASTDefine NULL ordering (PostgreSQL, SQLite)

Aggregation

COUNT(*) COUNT(spalte)All rows / rows with a value (without NULL)
SUM(x) AVG(x) MIN(x) MAX(x)Sum, average, minimum, maximum
COUNT(DISTINCT spalte)Count distinct values
GROUP BY kategorieForm groups
HAVING COUNT(*) > 1Filter groups after aggregation
SUM(CASE WHEN a THEN 1 ELSE 0 END)Conditional counting (pivot)

Joins

FROM a JOIN b ON b.a_id = a.idINNER JOIN – only matches on both sides
FROM a LEFT JOIN b ON b.a_id = a.idAll rows from a, NULL on the right if there is no match
LEFT JOIN b ON ... WHERE b.id IS NULLAnti-join: rows without a counterpart
FROM a CROSS JOIN bAll combinations (cross product)
FROM t x JOIN t y ON x.eltern_id = y.idSelf-join with aliases
FULL OUTER JOINAll rows from both sides (not in MySQL)

Subqueries & Sets

WHERE x > (SELECT AVG(x) FROM t)Scalar subquery
WHERE id IN (SELECT a_id FROM b)IN with a subquery
WHERE EXISTS (SELECT 1 FROM b WHERE b.a_id = a.id)Correlated existence check
WHERE NOT EXISTS (...)Safer than NOT IN with NULL
SELECT ... UNION ALL SELECT ...Stack results on top of each other (UNION removes duplicates)
... INTERSECT ... / ... EXCEPT ...Intersection / difference

Modifying data (DML)

INSERT INTO t (a, b) VALUES (1, 'x');Insert a row
INSERT INTO t (a, b) VALUES (1,'x'), (2,'y');Multiple rows at once
INSERT INTO t2 (a) SELECT a FROM t;Insert from a query
UPDATE t SET a = a + 1 WHERE id = 5;Change rows (do not forget WHERE)
DELETE FROM t WHERE id = 5;Delete rows
INSERT ... ON CONFLICT (id) DO UPDATE SET ...UPSERT (PostgreSQL, SQLite)
INSERT ... RETURNING id;Get generated values back (PostgreSQL, SQLite 3.35+)

Schema (DDL) & Constraints

CREATE TABLE t (id INTEGER PRIMARY KEY, ...);Create a table
x TEXT NOT NULL DEFAULT 'offen'Required field with a default value
CHECK (preis >= 0)Enforce a value range
UNIQUE (kunde_id, produkt_id)Combination allowed only once
FOREIGN KEY (kunde_id) REFERENCES kunden(id)Referential integrity
ALTER TABLE t ADD COLUMN x INTEGER;Add a column
DROP TABLE IF EXISTS t;Drop a table

CTE & Window functions

WITH x AS (SELECT ...) SELECT * FROM x;CTE: named subquery
WITH RECURSIVE r(n) AS (... UNION ALL ...) SELECT ...Recursive CTE (sequences, trees)
ROW_NUMBER() OVER (PARTITION BY g ORDER BY x)Number rows per group
RANK() / DENSE_RANK() OVER (ORDER BY x DESC)Ranking with / without gaps on ties
SUM(x) OVER (ORDER BY d)Running total
LAG(x) OVER (ORDER BY d) LEAD(x) OVER (...)Value of the previous / next row

Transactions, Indexes & Dialects

BEGIN; ... COMMIT; / ROLLBACK;Transaction (MySQL: START TRANSACTION)
SAVEPOINT s; ROLLBACK TO s;Partial rollback
CREATE INDEX idx ON t (spalte);Create an index
EXPLAIN QUERY PLAN SELECT ... (SQLite)Show the query plan
EXPLAIN (ANALYZE) SELECT ... (PostgreSQL)Plan with real run times
COALESCE(a, b) NULLIF(a, b)First non-NULL value / NULL if equal
GROUP_CONCAT(x) / STRING_AGG(x, ',')Values to text: SQLite, MySQL / PostgreSQL