SQL Quick Ref
A one-page cheat-sheet for every SQL clause you'll write — in the order they fire and the order you usually write them.
Full SELECT skeleton
SQL
WITH cte AS (SELECT …) -- common table expressions SELECT DISTINCT col1, AGG(col2) FROM table1 t1 JOIN table2 t2 ON t1.id = t2.t1_id WHERE cond GROUP BY col1 HAVING AGG(col2) > 10 ORDER BY col1 ASC LIMIT 20 OFFSET 40;
Mutate & manage
SQL
INSERT INTO t (a, b) VALUES (1, 2); INSERT INTO t (a, b) SELECT a, b FROM other; UPDATE t SET a = a + 1 WHERE id = 5; DELETE FROM t WHERE id = 5; TRUNCATE TABLE t;
Schema
SQL
CREATE TABLE t ( id BIGINT PRIMARY KEY, name VARCHAR(80) NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); ALTER TABLE t ADD col INT NOT NULL DEFAULT 0; DROP TABLE t; CREATE INDEX idx_t_name ON t (name); CREATE VIEW v AS SELECT id, name FROM t;
Transactions
SQL
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT; -- or ROLLBACK;
Aggregate templates
SQL
SELECT bucket,
COUNT(*) AS rows,
SUM(x) AS total,
AVG(x) AS mean,
MIN(x) AS lo,
MAX(x) AS hi
FROM t
GROUP BY bucket
HAVING COUNT(*) > 1
ORDER BY total DESC;
Tip: Bookmark this page in your browser. Even five years in, the skeleton query is the one you'll most often paste-and-edit.
Example
Example
SELECT col FROM t WHERE x = 1 GROUP BY y HAVING COUNT(*) > 1 ORDER BY z LIMIT 10;Try it Yourself »
Exercise
Commit a transaction with…
BEGIN; …;
;
Six letters; opposite of ROLLBACK.
Discussion
Loading…