Cheatsheets
SQL
SQL queries, joins, aggregation, DDL, and window functions.
36 entries
Query6
SELECT col1, col2 FROM tSelect specific columns
SELECT DISTINCT col FROM tUnique values only
... ORDER BY col DESCSort results (descending)
... LIMIT 10 OFFSET 20Paginate results
SELECT col AS aliasRename a column in output
SELECT name, count(*) AS n
FROM orders
GROUP BY name
HAVING count(*) > 5
ORDER BY n DESC;Full grouped + filtered query
Filtering7
WHERE col = 'x'Filter rows by a condition
WHERE a AND b / ORCombine conditions
WHERE col IN (1, 2, 3)Match any value in a list
WHERE col BETWEEN a AND bMatch a range (inclusive)
WHERE col LIKE 'a%'Pattern match (% = any chars)
WHERE col IS NULLMatch NULL values
WHERE EXISTS (SELECT 1 FROM ...)Correlated existence check
Joins5
SELECT *
FROM a
INNER JOIN b ON a.id = b.a_idRows matching in both tables
LEFT JOIN b ON ...All left rows + matches from right
RIGHT JOIN b ON ...All right rows + matches from left
FULL OUTER JOIN b ON ...All rows from both sides
CROSS JOIN bCartesian product of both tables
Aggregation6
COUNT(*) / SUM(col) / AVG(col)Aggregate functions
MIN(col) / MAX(col)Smallest / largest value
GROUP BY colGroup rows for aggregation
HAVING COUNT(*) > 1Filter groups (after GROUP BY)
COALESCE(a, b)First non-NULL value
STRING_AGG(col, ',')Concatenate grouped values
Modify & DDL7
INSERT INTO t (a) VALUES (1)Insert a row
UPDATE t SET a = 1 WHERE id = 2Update rows
DELETE FROM t WHERE id = 2Delete rows
INSERT INTO t (id, n) VALUES (1, 'a')
ON CONFLICT (id)
DO UPDATE SET n = EXCLUDED.n;Upsert (Postgres)
CREATE TABLE t (id INT PRIMARY KEY)Create a table
ALTER TABLE t ADD COLUMN c TEXTAdd a column
CREATE INDEX idx ON t(col)Create an index
Window & CTE5
ROW_NUMBER() OVER (ORDER BY col)Sequential row number
RANK() OVER (PARTITION BY a ORDER BY b)Rank within partitions
SUM(x) OVER (PARTITION BY a)Aggregate without collapsing rows
LAG(col) OVER (ORDER BY t)Value from the previous row
WITH recent AS (
SELECT * FROM orders
WHERE created > now() - interval '7 days'
)
SELECT * FROM recent;Common table expression (CTE)