SQL Cheat Sheet

A comprehensive reference for SQL syntax, functions, joins, and best practices. Print it, bookmark it, master it.

SELECT Queries

SELECT column1, column2 FROM table_name;Select specific columns from a table
SELECT * FROM table_name;Select all columns
SELECT DISTINCT column FROM table_name;Select unique values only
SELECT COUNT(*), AVG(col), SUM(col) FROM table;Aggregate functions

Filtering

SELECT * FROM t WHERE condition;Filter results with WHERE
SELECT * FROM t WHERE col IN (1, 2, 3);Filter by value list
SELECT * FROM t WHERE col BETWEEN a AND b;Filter by range
SELECT * FROM t WHERE col LIKE '%pattern%';Pattern matching
SELECT * FROM t WHERE col IS NULL;Check for NULL values

Joins

SELECT * FROM a JOIN b ON a.id = b.a_id;INNER JOIN (default)
SELECT * FROM a LEFT JOIN b ON a.id = b.a_id;LEFT JOIN — all rows from left table
SELECT * FROM a RIGHT JOIN b ON a.id = b.a_id;RIGHT JOIN — all rows from right table
SELECT * FROM a FULL JOIN b ON a.id = b.a_id;FULL OUTER JOIN — all rows from both
SELECT * FROM a CROSS JOIN b;CROSS JOIN — Cartesian product

Sorting & Grouping

SELECT * FROM t ORDER BY col ASC/DESC;Sort results
SELECT * FROM t ORDER BY col1, col2;Sort by multiple columns
SELECT col, COUNT(*) FROM t GROUP BY col;Group results
SELECT col, COUNT(*) FROM t GROUP BY col HAVING COUNT(*) > 1;Filter groups with HAVING
SELECT * FROM t LIMIT 10 OFFSET 20;Pagination with LIMIT and OFFSET

Modifying Data

INSERT INTO t (col1, col2) VALUES (v1, v2);Insert a single row
INSERT INTO t (col1, col2) VALUES (v1, v2), (v3, v4);Insert multiple rows
UPDATE t SET col1 = v1 WHERE condition;Update existing rows
DELETE FROM t WHERE condition;Delete rows
TRUNCATE TABLE t;Remove all rows (fast)

DDL — Schema

CREATE TABLE t (id INT PRIMARY KEY, name TEXT);Create a new table
ALTER TABLE t ADD COLUMN col TYPE;Add a column
ALTER TABLE t DROP COLUMN col;Remove a column
DROP TABLE t;Delete a table
CREATE INDEX idx_name ON t (col);Create an index

Subqueries & CTEs

SELECT * FROM t WHERE col IN (SELECT col FROM other);Subquery in WHERE
SELECT *, (SELECT MAX(col) FROM other) AS max FROM t;Subquery in SELECT
WITH cte AS (SELECT * FROM t) SELECT * FROM cte;Common Table Expression (CTE)

Window Functions

SELECT *, ROW_NUMBER() OVER (ORDER BY col) FROM t;Row numbering
SELECT *, RANK() OVER (PARTITION BY cat ORDER BY col) FROM t;Ranking within categories
SELECT *, LAG(col) OVER (ORDER BY col) FROM t;Access previous row value
SELECT *, SUM(col) OVER (PARTITION BY cat) FROM t;Running totals

Data Types (Common)

INTEGER / INTWhole numbers
BIGINTLarge whole numbers
DECIMAL(p, s) / NUMERICExact decimal numbers
VARCHAR(n) / TEXTVariable-length strings
BOOLEANTrue/false values
DATE / TIME / TIMESTAMPDate and time types
JSON / JSONBJSON data
UUIDUniversally unique identifier