appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Window functions

Lesson 3 of 412 minIntermediate

Compute rankings, running totals and comparisons without collapsing rows.

A window function computes a value across a set of related rows but, unlike GROUP BY, it keeps every row. You write it with OVER (...).

Total per user next to every order
SELECT id, user_id, total,
       SUM(total) OVER (PARTITION BY user_id) AS user_total
FROM orders;
  • PARTITION BY splits the rows into groups (like GROUP BY, but without merging).
  • ORDER BY inside OVER defines the order for ranking and running calculations.

Ranking

SELECT user_id, total,
       ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY total DESC) AS rn
FROM orders;
FunctionTies
ROW_NUMBER()Always unique: 1, 2, 3, 4
RANK()Ties share a rank and leave a gap: 1, 2, 2, 4
DENSE_RANK()Ties share a rank with no gap: 1, 2, 2, 3

Running totals and neighbours

SELECT created_at, total,
       SUM(total) OVER (ORDER BY created_at) AS running_total,
       LAG(total) OVER (ORDER BY created_at) AS previous_total
FROM orders;

LAG and LEAD read the previous and next row. Use them to compare a value with the one before it.

CarefulYou cannot use a window function in WHERE. To filter on a rank, put the query in a CTE or subquery and filter in the outer query.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What is the main difference between GROUP BY and a window function?
2. Scores 90, 80, 80, 70 with RANK() ordered descending. What is the rank of 70?
3. How do you keep only the top order per user using ROW_NUMBER()?

Key terms