SQL Joins, Window Functions and CTEs Cheat Sheet
Checked against SQL PostgreSQL 19 and MySQL 8.4 manuals; examples run on SQLite 3.51.0 on 28 November 2026. Each section links to the official docs it was checked against.
This sheet is for developers who can write a SELECT but still look up which join keeps which rows, or how to get a running total without a self-join. The syntax follows the PostgreSQL 19 and MySQL 8.4 reference manuals. I ran every query that SQLite also supports on sqlite3 3.51.0 against a small customers and orders table; rows that only apply to Postgres or MySQL are marked untested.
When to use what
Use INNER JOIN when a row without a match is useless to you, and LEFT JOIN when the left table is the list you are reporting on and the right side is optional detail. For "customers with no orders" I prefer NOT EXISTS over LEFT JOIN ... WHERE o.id IS NULL: it says what you mean and can't multiply rows. FULL OUTER JOIN exists in PostgreSQL but not in MySQL 8.4, where you combine a LEFT and a RIGHT join with UNION.
Reach for window functions whenever you need a per-row answer that depends on other rows: rank within a group, the previous value, a running total. They keep every row, where GROUP BY collapses them. Pick ROW_NUMBER when you need exactly one winner per group, RANK when ties should share a place and leave a gap, and DENSE_RANK when ties share a place without a gap.
CTEs are for readability first. Name each step of a long query, then select from the last one. Use WITH RECURSIVE for trees and series. The SQL joins post and the window functions post have longer walk-throughs, and the SQL query builder helps you draft a join before you run it.
MySQL's join grammar is at https://dev.mysql.com/doc/refman/8.4/en/join.html and lists INNER, CROSS, LEFT, RIGHT, NATURAL and STRAIGHT_JOIN, but no FULL join.
FROM customers c JOIN orders o ON o.customer_id = c.idInner join: keep only customers that have at least one order, one row per matching order
FROM customers c LEFT JOIN orders o ON o.customer_id = c.idKeep every customer; order columns are NULL for customers with no orders
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)Anti-join: customers with no orders at all
FROM customers c FULL OUTER JOIN orders o ON o.customer_id = c.idKeep unmatched rows from both sides; works in PostgreSQL and ran on SQLite 3.51, but MySQL 8.4 has no FULL join
FROM a JOIN b USING (customer_id)Join on same-named columns and output that column once
FROM sizes CROSS JOIN colorsEvery combination of the two tables, with no join condition
FROM users u, LATERAL (SELECT * FROM orders o WHERE o.user_id = u.id ORDER BY created_at DESC LIMIT 3) last3Run a subquery per row of the left table, here the three latest orders per user; PostgreSQL and MySQL 8.4 both accept LATERAL
MySQL's list is at https://dev.mysql.com/doc/refman/8.4/en/window-function-descriptions.html. Window functions are allowed only in the SELECT list and ORDER BY, so filter on them from an outer query or CTE.
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY day)Number each customer's orders 1, 2, 3 in date order, no ties
RANK() OVER (ORDER BY amount DESC)Rank by amount; ties share a rank and the next rank is skipped
DENSE_RANK() OVER (ORDER BY amount DESC)Rank by amount; ties share a rank and no numbers are skipped
LAG(amount) OVER (PARTITION BY customer_id ORDER BY day)Value from the previous row in the partition, NULL on the first row
LEAD(amount, 1, 0) OVER (PARTITION BY customer_id ORDER BY day)Value from the next row, with 0 instead of NULL on the last row
SUM(amount) OVER (PARTITION BY customer_id ORDER BY day)Running total per customer
... WINDOW w AS (PARTITION BY customer_id ORDER BY day)Name a window once and reuse it as OVER w in several columns
SELECT * FROM (SELECT ..., ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY amount DESC) rn FROM orders) t WHERE rn = 1Top row per group: the largest order for each customer
NTILE(4) OVER (ORDER BY amount)Split rows into four roughly equal buckets, for quartiles
With ORDER BY and no frame clause, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW in both manuals, which includes every peer row with the same sort value. MySQL 8.4 accepts only ROWS and RANGE units (https://dev.mysql.com/doc/refman/8.4/en/window-functions-frames.html); PostgreSQL also has GROUPS and EXCLUDE.
SUM(amount) OVER (ORDER BY day ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)Sum of this row and the one before it, a two-row moving total
SUM(amount) OVER (ORDER BY amount ROWS UNBOUNDED PRECEDING)Running total that counts tied rows one at a time instead of all at once
AVG(amount) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)Seven-row moving average
FIRST_VALUE(amount) OVER (PARTITION BY customer_id ORDER BY day)First value in the frame, here the customer's first order amount
SUM(amount) OVER (ORDER BY day GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW EXCLUDE CURRENT ROW)PostgreSQL only: frame by groups of peers and leave the current row out
count(*) FILTER (WHERE amount > 40) OVER (PARTITION BY customer_id)PostgreSQL only: count just the rows matching a condition inside the window
MySQL's version is at https://dev.mysql.com/doc/refman/8.4/en/with.html. MySQL stops a recursive CTE after cte_max_recursion_depth levels, 1000 by default.
WITH totals AS (SELECT customer_id, SUM(amount) t FROM orders GROUP BY customer_id) SELECT ... FROM totals JOIN customers ...Name an intermediate result and join to it like a table
WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM n WHERE x < 5) SELECT x FROM nGenerate the numbers 1 to 5; the WHERE in the recursive part is what stops it
WITH RECURSIVE tree AS (SELECT id, parent_id, 1 depth FROM nodes WHERE parent_id IS NULL UNION ALL SELECT n.id, n.parent_id, t.depth + 1 FROM nodes n JOIN tree t ON n.parent_id = t.id) SELECT * FROM treeWalk a parent/child table from the roots down, tracking depth
WITH x AS MATERIALIZED (SELECT ...)PostgreSQL only: force the CTE to be computed once instead of folded into the outer query
... ) SEARCH DEPTH FIRST BY id SET ordercolPostgreSQL only: add a column that orders a recursive result depth-first
SET SESSION cte_max_recursion_depth = 10000;MySQL only: allow deeper recursion than the default 1000 levels
Worked example: Latest order and running total per customer, in one pass
Five orders, one of them (customer 9) with no matching customer. This ran on sqlite3 3.51.0; the same SQL is valid in PostgreSQL 19 and MySQL 8.4.
SELECT customer_id, day, amount,
ROW_NUMBER() OVER w AS rn,
RANK() OVER (ORDER BY amount DESC) AS rnk,
LAG(amount) OVER w AS prev,
LEAD(amount, 1, 0) OVER w AS next,
SUM(amount) OVER w AS running
FROM orders WHERE customer_id = 1
WINDOW w AS (PARTITION BY customer_id ORDER BY day)
ORDER BY day;
customer_id day amount rn rnk prev next running
1 2026-11-01 30 1 2 50 30
1 2026-11-03 50 2 1 30 20 80
1 2026-11-05 20 3 3 50 0 100
prev is empty on the first row because LAG has nothing before it, while next shows 0 on the last row because I gave LEAD a default. running climbs 30, 80, 100. Then the frame trap: over all orders, SUM(amount) OVER (ORDER BY amount) returned 160 on both rows with amount 50, while the same sum with ROWS UNBOUNDED PRECEDING returned 110 and then 160. The default RANGE frame treats tied rows as one step. If you want a strict row-by-row running total, say ROWS and add a tiebreaker such as id to the ORDER BY.
Common mistakes
Putting a condition on the right table of a LEFT JOIN in the WHERE clause.
WHERE o.status = 'paid'removes the NULL rows and turns it into an inner join. Move the condition into the ON clause.Filtering on a window function in WHERE, like
WHERE ROW_NUMBER() OVER (...) = 1.Window functions run after WHERE. Compute them in a subquery or CTE and filter in the outer query.
Relying on the default frame for a running total when the ORDER BY column has duplicates.
Write
ROWS UNBOUNDED PRECEDINGexplicitly and make the ORDER BY unique.Writing
FULL OUTER JOINin a query that must also run on MySQL 8.4.Use a LEFT JOIN UNION a RIGHT JOIN, or check that you really need both unmatched sides.
A recursive CTE with no stopping condition on cyclic data.
Add a depth limit or a visited path check. PostgreSQL has a CYCLE clause; MySQL stops at
cte_max_recursion_depth.Using
ROW_NUMBERto pick 'the' top order when two orders tie.The winner is arbitrary. Add a tiebreaker column, or use
RANKif ties should all be returned.
Related cheat sheets
Sources
- https://www.postgresql.org/docs/current/queries-table-expressions.html
- https://www.postgresql.org/docs/current/tutorial-window.html
- https://www.postgresql.org/docs/current/functions-window.html
- https://www.postgresql.org/docs/current/sql-expressions.html
- https://www.postgresql.org/docs/current/queries-with.html
- https://dev.mysql.com/doc/refman/8.4/en/join.html
- https://dev.mysql.com/doc/refman/8.4/en/window-functions-usage.html
- https://dev.mysql.com/doc/refman/8.4/en/window-functions-frames.html
- https://dev.mysql.com/doc/refman/8.4/en/with.html
How we research: where our facts come from, how often we re-check them, and why no one can pay for a review or a verdict.