Skip to the content

Lesson 218 of 296

Window functions

What you will learn

  • What a window function is and how it differs from GROUP BY
  • OVER, PARTITION BY and ORDER BY
  • ROW_NUMBER, RANK and DENSE_RANK
  • Running totals
  • LAG and LEAD
  • The "top N per group" pattern
On this page

What is a window function?

GROUP BY collapses rows: many orders become one row per customer. A window function calculates across a set of related rows (the window) without collapsing them: every row stays, and gets an extra calculated value.

function() OVER (PARTITION BY ... ORDER BY ...)
  • PARTITION BY splits rows into groups (like GROUP BY, but rows are kept).
  • ORDER BY inside OVER sets the order within each partition (needed for ranking, running totals and LAG/LEAD).
  • An empty OVER () means the window is the whole result.

Ranking, running totals and change

SQL
WITH order_totals AS (
  SELECT o.id, o.customer_id, o.ordered_at,
         SUM(oi.quantity * oi.unit_price_pence) AS total_pence
  FROM orders o JOIN order_items oi ON oi.order_id = o.id
  WHERE o.status = 'paid'
  GROUP BY o.id
)
SELECT customer_id, id AS order_id, ordered_at, total_pence,
  ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY ordered_at) AS nth_order,
  SUM(total_pence) OVER (PARTITION BY customer_id ORDER BY ordered_at) AS running_total,
  total_pence - LAG(total_pence) OVER (PARTITION BY customer_id ORDER BY ordered_at) AS change_from_previous
FROM order_totals
ORDER BY customer_id, ordered_at;
customer_idorder_idordered_attotal_pencenth_orderrunning_totalchange_from_previous
11012026-06-01224812248NULL
11022026-06-15299925247751
31042026-07-02339913399NULL
31062026-08-01389827297499
  • ROW_NUMBER() numbers rows 1, 2, 3 within each customer.
  • SUM(...) OVER (... ORDER BY ...) gives a running total (the sum from the first row up to the current one).
  • LAG(x) reads the value from the previous row in the partition (NULL for the first); LEAD(x) reads the next row. Perfect for "change since last month" or "time between orders".

ROW_NUMBER vs RANK vs DENSE_RANK

The difference shows with ties:

SQL
SELECT score,
  ROW_NUMBER() OVER (ORDER BY score DESC) AS row_number,
  RANK()       OVER (ORDER BY score DESC) AS rank,
  DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank
FROM (VALUES (90), (85), (85), (70)) AS t(score);
scorerow_numberrankdense_rank
90111
85222
85322
70443
FunctionTiesGaps after ties
ROW_NUMBERDifferent numbers (arbitrary order between ties)n/a
RANKSame numberYes (2, 2, then 4)
DENSE_RANKSame numberNo (2, 2, then 3)

"Find the second-highest salary" is classic: use DENSE_RANK() = 2, so ties at the top do not break the answer.

Percentages of a total

SQL
SELECT name, category, price_pence,
  RANK() OVER (PARTITION BY category ORDER BY price_pence DESC) AS rank_in_category,
  ROUND(100.0 * price_pence / SUM(price_pence) OVER (), 1) AS pct_of_all
FROM products
ORDER BY category, rank_in_category;
namecategoryprice_pencerank_in_categorypct_of_all
Desk LampHome2999133.0
KettleKitchen3499138.5
MugKitchen89929.9
Pen SetStationery1250113.7
NotebookStationery45024.9

100.0 (not 100) makes the division decimal; integer division in SQL drops the fraction (7 / 2 is 3).

Top N per group

"The latest order for each customer" (or the top 3 products per category) is one of the most asked SQL questions. Window functions run after WHERE, so you cannot filter on them directly. Wrap the query and filter outside:

SQL
SELECT * FROM (
  SELECT c.name, o.id AS order_id, o.ordered_at,
         ROW_NUMBER() OVER (PARTITION BY o.customer_id ORDER BY o.ordered_at DESC) AS rn
  FROM orders o JOIN customers c ON c.id = o.customer_id
) latest
WHERE rn = 1
ORDER BY name;
nameorder_idordered_atrn
Aisha Khan1022026-06-151
Ben Smith1032026-06-201
Chen Li1062026-08-011
Dara Patel1052026-07-101

Change rn = 1 to rn <= 3 for the top 3. PostgreSQL also has the shortcut SELECT DISTINCT ON (customer_id) ... ORDER BY customer_id, ordered_at DESC for the top 1.

Frames

For moving averages, the frame clause sets which rows around the current one are included: AVG(total) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) gives a 7-day moving average.

How to say it in an interview

"Window functions compute across related rows without collapsing them, using OVER with PARTITION BY to group and ORDER BY to order within each group. I use ROW_NUMBER, RANK and DENSE_RANK for ranking, where RANK leaves gaps after ties and DENSE_RANK does not, SUM OVER ordered for running totals, and LAG and LEAD for comparing with the previous or next row. For top N per group I number rows per partition in a subquery or CTE and filter rn less than or equal to N outside, because window functions run after WHERE."

Key words

WordMeaning
Window functionCalculates across related rows without collapsing them
OVERDefines the window
PARTITION BYSplits rows into groups for the window
ROW_NUMBER / RANK / DENSE_RANKNumbering and ranking functions
Running totalA cumulative sum up to the current row
LAG / LEADValue from the previous / next row
FrameWhich neighbouring rows a window includes

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.