all cheat sheets

SQL window functions cheat sheet

ROW_NUMBER, RANK, running totals, LAG/LEAD and moving averages in one page.

RANK() OVER (PARTITION BY category ORDER BY price DESC) — the numbering restarts in every partition, and rows are kept.
Hardware329.50rank 1
Hardware129.00rank 2
Hardware59.00rank 3
Audio249.99rank 1
Audio199.00rank 2

Ranking

ROW_NUMBER / RANK / DENSE_RANK
SELECT name, price,
  ROW_NUMBER() OVER (ORDER BY price DESC) AS rn,
  RANK()       OVER (ORDER BY price DESC) AS rnk,
  DENSE_RANK() OVER (ORDER BY price DESC) AS drnk
FROM products;
Top N per group
SELECT * FROM (
  SELECT category, name, price,
    ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS rn
  FROM products
) WHERE rn <= 2;

Running values and neighbours

Running total
SELECT order_date,
  SUM(1) OVER (ORDER BY order_date) AS orders_so_far
FROM orders;
LAG / LEAD — previous and next row
SELECT customer_id, order_date,
  LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) AS prev_order
FROM orders;
3-row moving average
SELECT id, price,
  AVG(price) OVER (ORDER BY id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS ma3
FROM products;

Try it live

sql · editable
loading editor…

Practice it

learn sql step by step →

More cheat sheets

Ready for interview-level questions? Pro unlocks the full company problem set.