143 commands · 9 cheat sheets · SQL

Querying and Joins master quick reference

Browse 143 commands from 9 focused cheat sheets on page 1 of 1. Each example opens its matching detailed section.

Querying and Joins · 19 commands

PostgreSQL Aggregates and Grouping Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Count rowsSELECT COUNT(*) FROM orders;View examples
Count non-null valuesSELECT COUNT(shipped_at) FROM orders;View examples
Count distinct valuesSELECT COUNT(DISTINCT customer_id) FROM orders;View examples
Sum and average valuesSELECT SUM(amount), AVG(amount) FROM payments;View examples
Find range endpointsSELECT MIN(created_at), MAX(created_at) FROM events;View examples
Group equal valuesSELECT status, COUNT(*) FROM orders GROUP BY status;View examples
Group by several expressionsSELECT region, status, SUM(amount) FROM orders GROUP BY region, status;View examples
Filter detail rowsSELECT team, SUM(score) FROM results WHERE season = 2026 GROUP BY team;View examples
Filter summary groupsSELECT team, SUM(score) FROM results GROUP BY team HAVING SUM(score) >= 100;View examples
Filter one aggregateCOUNT(*) FILTER (WHERE status = 'paid') AS paid_countView examples
Sum selected valuesSUM(amount) FILTER (WHERE status = 'paid') AS paid_totalView examples
Join text in orderSTRING_AGG(name, ', ' ORDER BY name) AS namesView examples
Collect values in orderARRAY_AGG(id ORDER BY created_at, id) AS idsView examples
Require every conditionBOOL_AND(approved) AS all_approvedView examples
Choose several summariesGROUP BY GROUPING SETS ((region, product), (region), ())View examples
Build hierarchical subtotalsGROUP BY ROLLUP (region, product)View examples
Build all subtotal combinationsGROUP BY CUBE (region, channel)View examples
Identify subtotal columnsGROUPING(region, product) AS grouping_maskView examples
Default an empty totalCOALESCE(SUM(amount), 0) AS totalView examples

Querying and Joins · 15 commands

PostgreSQL CTEs and Subqueries Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Return one valueSELECT name, ( SELECT max(total) FROM orders ) AS largest FROM customers;View examples
Match any returned valueWHERE customer_id IN ( SELECT customer_id FROM vip_customers )View examples
Test whether a row existsWHERE EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.id )View examples
Test whether no row existsWHERE NOT EXISTS ( SELECT 1 FROM orders o WHERE o.customer_id = c.id )View examples
Reference the outer rowSELECT c.id, ( SELECT count(*) FROM orders o WHERE o.customer_id = c.id ) FROM customers c;View examples
Query an inline tableFROM ( SELECT customer_id, sum(total) AS spent FROM orders GROUP BY customer_id ) AS totalsView examples
Reference earlier FROM itemsCROSS JOIN LATERAL ( SELECT * FROM orders WHERE customer_id = c.id ORDER BY created_at DESC LIMIT 1 ) AS latestView examples
Name a query componentWITH active AS ( SELECT * FROM users WHERE active ) SELECT * FROM active;View examples
Chain CTEsWITH base AS (...), summarized AS ( SELECT ... FROM base ) SELECT * FROM summarized;View examples
Force one materializationWITH report AS MATERIALIZED ( SELECT expensive_fn(id) AS value FROM items ) SELECT * FROM report;View examples
Permit parent optimizationWITH filtered AS NOT MATERIALIZED ( SELECT * FROM events ) SELECT * FROM filtered WHERE kind = 'error';View examples
Start a recursive queryWITH RECURSIVE numbers(n) AS ( VALUES (1) UNION ALL SELECT n + 1 FROM numbers WHERE n < 5 ) SELECT * FROM numbers;View examples
Deduplicate recursive resultsseed_query UNION recursive_queryView examples
Consume changed rowsWITH moved AS ( DELETE FROM queue WHERE done RETURNING * ) INSERT INTO archive SELECT * FROM moved;View examples
Update from a CTEWITH changes AS (...) UPDATE products p SET price = c.price FROM changes c WHERE p.id = c.id;View examples

Querying and Joins · 13 commands

PostgreSQL Cursors and Batched Fetching Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Declare forward-only cursorDECLARE export_rows NO SCROLL CURSOR FOR SELECT id, created_at FROM app.events ORDER BY id;View examples
Fetch a bounded batchFETCH FORWARD 500 FROM export_rows;View examples
Close a cursorCLOSE export_rows;View examples
Inspect session cursorsSELECT name, is_holdable, is_scrollable, creation_time FROM pg_cursors;View examples
Declare scrolling cursorDECLARE audit_scan SCROLL CURSOR FOR SELECT event_id, occurred_at FROM app.audit_events ORDER BY event_id;View examples
Fetch one absolute rowFETCH ABSOLUTE 1000 FROM audit_scan;View examples
Move without returning rowsMOVE FORWARD 500 FROM audit_scan;View examples
Keep a cursor after commitDECLARE export_hold NO SCROLL CURSOR WITH HOLD FOR SELECT id, payload FROM app.events ORDER BY id;View examples
Lock rows as fetchedDECLARE jobs NO SCROLL CURSOR FOR SELECT job_id FROM app.jobs WHERE state = 'ready' ORDER BY job_id FOR UPDATE SKIP LOCKED;View examples
Update current cursor rowUPDATE app.jobs SET state = 'claimed' WHERE CURRENT OF jobs;View examples
Return a refcursorOPEN c FOR SELECT id FROM app.events ORDER BY id; RETURN c;View examples
Fetch a resumable keyset batchSELECT id, payload FROM app.events WHERE id > 50000 ORDER BY id LIMIT 500;View examples
Bound cursor transaction timeSET LOCAL idle_in_transaction_session_timeout = '60s';View examples

Querying and Joins · 16 commands

PostgreSQL LATERAL Joins and Set-Returning Functions Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Join a correlated subquerySELECT c.id, x.id FROM app.customers c CROSS JOIN LATERAL ( SELECT id FROM app.orders WHERE customer_id = c.id ) x;View examples
Return top one per rowSELECT c.id, x.id FROM app.customers c CROSS JOIN LATERAL ( SELECT id FROM app.orders WHERE customer_id = c.id ORDER BY created_at DESC LIMIT 1 ) x;View examples
Make lateral explicitSELECT t.id, f.value FROM app.things t CROSS JOIN LATERAL app.expand(t.payload) AS f(value);View examples
Preserve unmatched outer rowsSELECT c.id, x.id FROM app.customers c LEFT JOIN LATERAL ( SELECT id FROM app.orders WHERE customer_id = c.id LIMIT 1 ) x ON true;View examples
Filter after optional expansionSELECT c.id, x.id FROM app.customers c LEFT JOIN LATERAL app.lookup(c.id) x ON true WHERE x.id IS NULL;View examples
Generate integersSELECT n FROM generate_series(1, 10, 1) AS g(n);View examples
Generate daily timestampsSELECT ts FROM generate_series(timestamp '2026-08-01', timestamp '2026-08-07', interval '1 day') AS g(ts);View examples
Expand an arraySELECT value FROM unnest(ARRAY[10,20,30]) AS u(value);View examples
Add ordinalitySELECT value, position FROM unnest(ARRAY[10,20]) WITH ORDINALITY AS u(value, position);View examples
Zip arrays in FROMSELECT * FROM unnest(ARRAY[1,2], ARRAY['a','b']) AS u(id, label);View examples
Expand a JSON arraySELECT value FROM jsonb_array_elements('[1,2,3]'::jsonb) AS j(value);View examples
Project JSON objectsSELECT * FROM jsonb_to_recordset('[{"id":1}]'::jsonb) AS x(id integer);View examples
Declare estimated SRF rowsALTER FUNCTION app.recent_orders(bigint, integer) ROWS 10;View examples
Call a table functionSELECT * FROM app.recent_orders(42, 5);View examples
Inspect without executionEXPLAIN SELECT * FROM app.customers c CROSS JOIN LATERAL app.recent_orders(c.customer_id, 3) r;View examples
Measure lateral loopsEXPLAIN (ANALYZE, BUFFERS) SELECT * FROM app.customers c CROSS JOIN LATERAL app.recent_orders(c.customer_id, 3) r;View examples

Querying and Joins · 11 commands

PostgreSQL NULLs and Conditional Expressions Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Test for nullWHERE deleted_at IS NULLView examples
Test for a valueWHERE email IS NOT NULLView examples
Null-safe inequalityold_value IS DISTINCT FROM new_valueView examples
Null-safe equalityleft_value IS NOT DISTINCT FROM right_valueView examples
First non-null valueCOALESCE(display_name, username, 'Anonymous')View examples
Convert equality to nullNULLIF(denominator, 0)View examples
Searched CASECASE WHEN score >= 90 THEN 'A' WHEN score >= 80 THEN 'B' ELSE 'C' ENDView examples
Simple CASECASE status WHEN 'open' THEN 1 WHEN 'closed' THEN 0 ELSE NULL ENDView examples
Count non-null valuesCOUNT(completed_at)View examples
Count all rowsCOUNT(*)View examples
Place nulls lastORDER BY priority DESC NULLS LASTView examples

Querying and Joins · 16 commands

PostgreSQL Recursive Queries and Graph Traversal Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Generate a bounded sequenceWITH RECURSIVE t(n) AS ( VALUES (1) UNION ALL SELECT n + 1 FROM t WHERE n < 10 ) SELECT n FROM t;View examples
Walk childrenWITH RECURSIVE t(id) AS ( VALUES (42::bigint) UNION ALL SELECT e.to_id FROM app.edges e JOIN t ON e.from_id=t.id ) SELECT * FROM t;View examples
Remove duplicate rowsWITH RECURSIVE t(id) AS ( VALUES (1::bigint) UNION SELECT to_id FROM app.edges JOIN t ON from_id=t.id ) SELECT id FROM t;View examples
Cap traversal depthWITH RECURSIVE t(n,d) AS ( VALUES (1,0) UNION ALL SELECT n+1,d+1 FROM t WHERE d<20 ) SELECT * FROM t;View examples
Set a statement budgetSET LOCAL statement_timeout = '10s';View examples
Append to a pathSELECT ARRAY[1,2] || 3;View examples
Test path membershipSELECT 3 = ANY (ARRAY[1,2,3]);View examples
Declare cycle detectionWITH RECURSIVE t(id) AS ( VALUES (1::bigint) UNION ALL SELECT to_id FROM app.edges JOIN t ON from_id=t.id ) CYCLE id SET cyc USING path SELECT * FROM t;View examples
Filter cycle-closing rowsSELECT id, path FROM walk WHERE NOT is_cycle;View examples
Create depth-first orderWITH RECURSIVE t(id) AS ( VALUES (1::bigint) UNION ALL SELECT to_id FROM app.edges JOIN t ON from_id=t.id ) SEARCH DEPTH FIRST BY id SET ord SELECT * FROM t;View examples
Create breadth-first orderWITH RECURSIVE t(id) AS ( VALUES (1::bigint) UNION ALL SELECT to_id FROM app.edges JOIN t ON from_id=t.id ) SEARCH BREADTH FIRST BY id SET ord SELECT * FROM t;View examples
Order final outputSELECT id FROM tree ORDER BY bfs_order, id;View examples
Count reachable verticesSELECT count(*) FROM reachable;View examples
Aggregate by depthSELECT depth, count(*) FROM walk GROUP BY depth ORDER BY depth;View examples
Index outbound edgesCREATE INDEX CONCURRENTLY edges_from_id_idx ON app.edges (from_id);View examples
Plan without traversalEXPLAIN WITH RECURSIVE t(n) AS ( VALUES (1) UNION ALL SELECT n+1 FROM t WHERE n<10 ) SELECT * FROM t;View examples

Querying and Joins · 16 commands

PostgreSQL Window Functions Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Count without groupingCOUNT(*) OVER () AS row_countView examples
Total each partitionSUM(amount) OVER (PARTITION BY department) AS department_totalView examples
Number rowsROW_NUMBER() OVER (PARTITION BY team ORDER BY score DESC, id ) AS positionView examples
Rank with gapsRANK() OVER (ORDER BY score DESC) AS rankView examples
Rank without gapsDENSE_RANK() OVER (ORDER BY score DESC) AS dense_rankView examples
Split into bucketsNTILE(4) OVER (ORDER BY score DESC) AS quartileView examples
Read the previous rowLAG(revenue) OVER (PARTITION BY product_id ORDER BY month ) AS previous_revenueView examples
Read the next rowLEAD(revenue) OVER (PARTITION BY product_id ORDER BY month ) AS next_revenueView examples
Read the first valueFIRST_VALUE(price) OVER (PARTITION BY sku ORDER BY changed_at ) AS initial_priceView examples
Read the partition's last valueLAST_VALUE(price) OVER (PARTITION BY sku ORDER BY changed_at ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) AS final_priceView examples
Calculate a running totalSUM(amount) OVER ( ORDER BY occurred_at, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS running_totalView examples
Calculate a moving averageAVG(amount) OVER ( ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ) AS three_row_averageView examples
Calculate percent of total100.0 * amount / NULLIF(SUM(amount) OVER (), 0) AS percent_totalView examples
Reuse a window definitionWINDOW by_account AS (PARTITION BY account_id ORDER BY occurred_at )View examples
Filter a window resultWITH ranked AS (...) SELECT * FROM ranked WHERE row_number = 1;View examples
Order the final resultSELECT ... ORDER BY department, rank, employee_id;View examples

Querying and Joins · 16 commands

SQL Joins Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Keep matching rowsSELECT o.id, c.name FROM orders AS o INNER JOIN customers AS c ON c.id = o.customer_id;View examples
Alias joined tablesSELECT o.id, c.name FROM orders AS o JOIN customers AS c ON c.id = o.customer_id;View examples
Join shared column namesSELECT order_id, status FROM orders JOIN shipments USING (order_id);View examples
Keep every left rowSELECT c.name, o.id FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.id;View examples
Find unmatched left rowsSELECT c.id FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.id WHERE o.id IS NULL;View examples
Filter joined matchesSELECT c.name, o.id FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.id AND o.status = 'paid';View examples
Keep every right rowSELECT c.name, o.id FROM customers AS c RIGHT JOIN orders AS o ON o.customer_id = c.id;View examples
Keep both sidesSELECT a.email, s.email FROM app_users AS a FULL OUTER JOIN subscribers AS s ON s.email = a.email;View examples
Merge an outer-join keySELECT COALESCE(a.email, s.email) AS email FROM app_users AS a FULL JOIN subscribers AS s ON s.email = a.email;View examples
Create every combinationSELECT c.color, s.size FROM colors AS c CROSS JOIN sizes AS s;View examples
Join a table to itselfSELECT e.name, m.name AS manager FROM employees AS e LEFT JOIN employees AS m ON m.id = e.manager_id;View examples
Chain several joinsSELECT o.id, c.name, p.name FROM orders AS o JOIN customers AS c ON c.id = o.customer_id JOIN products AS p ON p.id = o.product_id;View examples
Match multiple columnsSELECT i.sku, p.price FROM inventory AS i JOIN prices AS p ON p.sku = i.sku AND p.region = i.region;View examples
Count related rowsSELECT c.id, COUNT(o.id) AS order_count FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.id GROUP BY c.id;View examples
Sum related valuesSELECT c.id, COALESCE(SUM(o.total), 0) AS revenue FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.id GROUP BY c.id;View examples
Join a correlated subquerySELECT c.id, latest.id FROM customers AS c LEFT JOIN LATERAL ( SELECT o.id FROM orders AS o WHERE o.customer_id = c.id ORDER BY o.created_at DESC LIMIT 1 ) AS latest ON true;View examples

Querying and Joins · 21 commands

SQL SELECT Queries Cheat Sheet

Open full cheat sheet
UseSyntaxExamples
Select columnsSELECT id, name FROM customers;View examples
Rename an output columnSELECT total AS order_total FROM orders;View examples
Remove duplicate rowsSELECT DISTINCT country FROM customers;View examples
Filter by comparisonSELECT * FROM orders WHERE total >= 100;View examples
Require every conditionSELECT * FROM orders WHERE status = 'paid' AND total >= 100;View examples
Accept either conditionSELECT * FROM orders WHERE status = 'new' OR status = 'processing';View examples
Match a value listSELECT * FROM orders WHERE status IN ('new', 'processing');View examples
Match an inclusive rangeSELECT * FROM orders WHERE total BETWEEN 50 AND 100;View examples
Find missing valuesSELECT * FROM customers WHERE phone IS NULL;View examples
Match a text patternSELECT * FROM customers WHERE name LIKE 'A%';View examples
Sort the resultSELECT * FROM orders ORDER BY created_at DESC, id ASC;View examples
Limit returned rowsSELECT * FROM orders ORDER BY created_at DESC FETCH FIRST 10 ROWS ONLY;View examples
Skip result rowsSELECT * FROM orders ORDER BY id OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;View examples
Count rowsSELECT COUNT(*) AS order_count FROM orders;View examples
Sum a columnSELECT SUM(total) AS revenue FROM orders WHERE status = 'paid';View examples
Aggregate by groupSELECT status, COUNT(*) FROM orders GROUP BY status;View examples
Filter grouped resultsSELECT customer_id, SUM(total) FROM orders GROUP BY customer_id HAVING SUM(total) >= 500;View examples
Join matching rowsSELECT o.id, c.name FROM orders AS o INNER JOIN customers AS c ON c.id = o.customer_id;View examples
Keep every left rowSELECT c.name, o.id FROM customers AS c LEFT JOIN orders AS o ON o.customer_id = c.id;View examples
Test for related rowsSELECT * FROM customers AS c WHERE EXISTS ( SELECT 1 FROM orders AS o WHERE o.customer_id = c.id );View examples
Name an intermediate queryWITH paid_orders AS ( SELECT * FROM orders WHERE status = 'paid' ) SELECT * FROM paid_orders;View examples
CMDMEMO TERMINALREAD ONLY