What this page is for

Intent: the full picture behind the quick Window functions page. Same sections, same order, with every step table, the wrong version of each query, and the harder interview questions.
Read the quick page first. Each section here starts where the quick one stops.
Time: about 20 minutes.

Words you need first

Everything from the quick page (window function, OVER, PARTITION BY, ORDER BY inside OVER, CTE, LAG and LEAD, NULL), plus:

  • Frame: the exact rows inside one pile that a window function looks at, for the current row. It is set with words like ROWS BETWEEN ... AND CURRENT ROW. If you don’t write one, the database uses a default.
  • Default frame: with ORDER BY and no frame written, the frame runs from the first row of the pile to the current row.
  • Peers: rows that have the same ORDER BY value inside their pile. They tie, so the default frame treats them as one step.
  • Pile (partition): one group made by PARTITION BY. Each pile is worked on separately, and the numbering or running total restarts for each pile.
  • Calendar table: a table with one row per day, used to show days that have no orders.

Window functions are part of the SQL standard and work in Postgres, MySQL 8 and later, SQL Server and Oracle. The examples use Postgres.

Why it exists

GROUP BY answers “one row per restaurant”. Many questions need every row plus a number about its group. A window function adds that number to each row. The page follows the three jobs from the quick page: top N per group, running totals, and the previous row.

The picture

One pile of four rows, three ways to write OVER

The same picture as the quick page. The OVER () column is the whole pile. The ORDER BY column is the pile up to and including the current row. The PARTITION BY column restarts for each restaurant.

How it works, with an example

Simply: A window function gives every row a value that uses related rows, and it does not squash the rows the way GROUP BY does. Think of a shop counter where every bill stays on the counter, and each bill gets a note from its own group, such as its rank or its running total. Window functions run after WHERE, GROUP BY and HAVING, so you cannot filter a rank in WHERE.

What to know: You write a window function with OVER, which says which rows make up its window. PARTITION BY splits the rows into piles and restarts the function in each pile, and ORDER BY inside OVER sets the order inside each pile. The window runs after WHERE, GROUP BY and HAVING and before the final ORDER BY, so it cannot go in WHERE.

The same slots recipe and run order as the quick page: FROM and JOIN, WHERE, GROUP BY, HAVING, the window functions, SELECT, then the final ORDER BY. Because the window comes after GROUP BY, it can use aggregates such as sum(...) in its ORDER BY.

Slots recipe. Keep the rows? Yes, so use a window function. No, use GROUP BY.

  1. Which function: rank(), sum(), lag().
  2. PARTITION BY: “per”, “for each”, “within”, “its”. It restarts per group.
  3. ORDER BY inside OVER: “so far”, “running”, “top”, “previous”.

The most common mistake

Forgetting that PARTITION BY restarts the count

With rank() OVER (PARTITION BY restaurant ORDER BY revenue DESC), every restaurant is its own pile and counting starts at 1 in each one. So Masala Dosa is rank 1 in Dosa Den, not rank 3. A common slip is to count down the whole table anyway. Rank 3 only happens when PARTITION BY is left out: then rank() OVER (ORDER BY revenue DESC) ranks Paneer Tikka 1, Dal Makhani 2, Masala Dosa 3 in one pile.

rank() and top N per group

Simply: Each restaurant has its own shelf of dishes. PARTITION BY sets up one shelf for each restaurant, and rank() puts the dishes on each shelf in order, best first, counting from 1 on every shelf. The top dish of each restaurant is the one with rank 1, so you keep only rank 1.

What to know: rank() numbers the rows inside each PARTITION BY pile, in the order set by ORDER BY inside OVER, and the numbering restarts for each pile. WHERE runs before the window, so put rank() in a CTE and filter the rank outside.

Example. Top dish by revenue in each restaurant, delivered orders only (the SQL and Drizzle are the same as on the quick page).

WITH ranked AS (
  SELECT r.name AS restaurant, m.name AS item,
         sum(oi.qty * m.price) AS revenue,
         rank() OVER (PARTITION BY r.id ORDER BY sum(oi.qty * m.price) DESC) AS rnk
  FROM orders o
  JOIN restaurants r ON r.id = o.restaurant_id
  JOIN order_items oi ON oi.order_id = o.id
  JOIN menu_items m ON m.id = oi.menu_item_id
  WHERE o.status = 'delivered'
  GROUP BY m.id, m.name, r.id, r.name
)
SELECT restaurant, item, revenue FROM ranked WHERE rnk = 1;
const revenue = sql<number>`sum(${orderItems.qty} * ${menuItems.price})`.mapWith(Number);
const ranked = db.$with('ranked').as(
  db.select({
    restaurant: restaurants.name,
    item: menuItems.name,
    revenue: revenue.as('revenue'),
    rnk: sql<number>`rank() over (partition by ${restaurants.id} order by ${revenue} desc)`.as('rnk'),
  })
  .from(orders)
  .innerJoin(restaurants, eq(restaurants.id, orders.restaurantId))
  .innerJoin(orderItems, eq(orderItems.orderId, orders.id))
  .innerJoin(menuItems, eq(menuItems.id, orderItems.menuItemId))
  .where(eq(orders.status, 'delivered'))
  .groupBy(menuItems.id, menuItems.name, restaurants.id, restaurants.name)
);
const top = await db.with(ranked).select().from(ranked).where(eq(ranked.rnk, 1));

Step 1, after the joins (6 order lines, including the cancelled order 103):

orderrestaurantitemqty x price
101Spice HubPaneer Tikka2 x 250 = 500
101Spice HubDal Makhani1 x 200 = 200
102Dosa DenMasala Dosa3 x 120 = 360
103Burger BayClassic Burger2 x 180 = 360
104Spice HubDal Makhani2 x 200 = 400
105Spice HubPaneer Tikka1 x 250 = 250

Step 2, after WHERE (order 103 removed, 5 lines). Step 3, the GROUP BY makes one pile per dish:

item (pile)linesrevenue
Paneer Tikka500, 250750
Dal Makhani200, 400600
Masala Dosa360360

Step 4, after the window (rank counted inside each restaurant):

restaurantitemrevenuernk
Spice HubPaneer Tikka7501
Spice HubDal Makhani6002
Dosa DenMasala Dosa3601

Step 5, the outer WHERE rnk = 1. Result: Spice Hub, Paneer Tikka, 750 and Dosa Den, Masala Dosa, 360. Burger Bay has no row, because its only order was cancelled and WHERE removed it.

The wrong versions, and what they return

  • Grouped by the order, not the dish: GROUP BY o.id, ... makes one pile per order. Order 101 has two dishes, so the item name is neither grouped nor aggregated, and Postgres stops with “column menu_items.name must appear in the GROUP BY clause or be used in an aggregate function”.
  • PARTITION BY price instead of restaurant: each dish has its own price (250, 200, 120), so each dish is alone in its pile and gets rank 1. All three dishes come back from WHERE rnk = 1, including the ones that are not the top dish of their restaurant.
  • No PARTITION BY at all: the ranks are 1, 2, 3 across all three dishes, so Masala Dosa gets 3 and only Paneer Tikka comes back from WHERE rnk = 1.

Why this, not that

  • GROUP BY restaurant vs PARTITION BY restaurant: GROUP BY would give one row per restaurant, and the dish rows would be gone. PARTITION BY keeps every dish row and only sets the pile the rank is counted in.
  • CTE, then filter outside vs WHERE rnk = 1 in one query: WHERE runs before the window, so the rank doesn’t exist yet. Postgres refuses with “window functions are not allowed in WHERE”. The CTE makes the rank a real column, and the outer query can filter it.
  • Ties, one line each. With the tie example values 90, 90, 80 (a generic illustration, not the food data):
valuerank()dense_rank()row_number()
90111 (or 2, arbitrary)
90112 (or 1, arbitrary)
80323

rank() skips to 3 after the tie. dense_rank() goes to 2. row_number() gives a unique number, so which 90 gets 1 is arbitrary. This matters for “top N”: rank() <= N can return more than N rows when there are ties at the cut-off, row_number() <= N always returns exactly N.

  • Repeat the expression, don’t use the alias: in Postgres you can’t write OVER (ORDER BY revenue DESC) using the alias revenue from the same SELECT. That is why the Drizzle code reuses the revenue SQL object inside rank() over (...).

Trigger card

When I see “top N per X”, I use rank() OVER (PARTITION BY X ORDER BY value DESC) in a CTE and filter rnk <= N outside, because WHERE runs before the window and the rank has to exist first.

Running total

Simply: A running total adds up the rows so far, in order, and writes the total on each row. Think of a bank passbook, where every line shows the amount and the balance so far. In SQL, sum() with ORDER BY inside OVER does this, so each row adds everything up to itself.

What to know: sum(x) OVER (ORDER BY time) adds the current row to all the rows before it in that order. OVER () gives the whole total on every row, and with no OVER at all, the rows collapse into one row.

Example. order_totals has one row per delivered order. Here are the four ways to write OVER, with a fifth column that adds PARTITION BY restaurant_id:

order_idtotalOVER ()OVER (ORDER BY created_at)OVER (PARTITION BY restaurant_id ORDER BY created_at)
1017001710700700 (Spice Hub)
10236017101060360 (Dosa Den)
104400171014601100 (Spice Hub)
105250171017101350 (Spice Hub)

With no OVER at all, sum(total) collapses the four rows into one row showing 1710, and you can’t select order_id beside it.

Now the daily running total, with its two layers. (The SQL and Drizzle are the same as on the quick page.)

WITH daily AS (
  SELECT o.created_at::date AS day, sum(oi.qty * m.price) AS revenue
  FROM orders o
  JOIN order_items oi ON oi.order_id = o.id
  JOIN menu_items m ON m.id = oi.menu_item_id
  WHERE o.status = 'delivered'
  GROUP BY o.created_at::date
)
SELECT day, revenue, sum(revenue) OVER (ORDER BY day) AS running_total
FROM daily
ORDER BY day;
const day = sql<string>`${orders.createdAt}::date`;
const daily = db.$with('daily').as(
  db.select({ day: day.as('day'), revenue: sql<number>`sum(${orderItems.qty} * ${menuItems.price})`.mapWith(Number).as('revenue') })
    .from(orders)
    .innerJoin(orderItems, eq(orderItems.orderId, orders.id))
    .innerJoin(menuItems, eq(menuItems.id, orderItems.menuItemId))
    .where(eq(orders.status, 'delivered'))
    .groupBy(day)
);
const rows = await db.with(daily).select({
  day: daily.day, revenue: daily.revenue,
  runningTotal: sql<number>`sum(${daily.revenue}) over (order by ${daily.day})`.mapWith(Number),
}).from(daily).orderBy(daily.day);

Step 1, after WHERE (order 103 removed). Each line is already a sum of qty x price:

dayorderline total
2026-10-28101500
2026-10-28101200
2026-10-28102360
2026-10-30104400
2026-10-31105250

Step 2, the GROUP BY day makes one pile per day (layer 1):

dayrevenue
2026-10-28500 + 200 + 360 = 1060
2026-10-30400
2026-10-31250

Step 3, the window over the daily rows (layer 2, the result):

dayrevenuerunning_total
2026-10-2810601060
2026-10-304001460
2026-10-312501710

There is no 2026-10-29 row. Its only order was cancelled, so no rows were left for that day, and a day with no rows makes no pile.

The wrong versions, and what they return

  • GROUP BY revenue: Postgres refuses, because an aggregate can’t be a GROUP BY key. You want one row per day, so group by the day.
  • OVER () for the running total: the window covers the whole daily set, so the answer on every row is 1710:
dayrevenuerunning_total (wrong)
2026-10-2810601710
2026-10-304001710
2026-10-312501710
  • Skipping the first layer: putting the window on the order lines gives a running total per order line, not per day. Build the daily rows in the CTE first.

Why this, not that

  • OVER () vs OVER (ORDER BY day) vs no OVER: the table above. OVER () is the whole pile for every row. ORDER BY inside OVER gives the running total. No OVER collapses everything into one row.
  • Group by the day first, then the window: the first layer answers “what did each day make?”, the second answers “what has been made so far?”. Mixing them into one query, with the window on the order lines, answers a different question.
  • Default frame in full: with ORDER BY and no frame written, Postgres uses RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. That means the pile from its first row to the current row, and every peer (a row with the same ORDER BY value) counts together. So if two rows share the same ORDER BY value, they get the same running total, and that total includes both of them. The frame is the reason the running total works, and it is also why ties behave as they do.
  • Days with no rows: a calendar table with one row per day, joined with LEFT JOIN to the daily CTE, gives 2026-10-29 a row with revenue NULL. Wrap it in COALESCE(revenue, 0) to show 0, and the running total stays 1060 on that day.

Trigger card

When I see “running total”, “cumulative” or “so far”, I use sum(x) OVER (ORDER BY time), because the ORDER BY inside OVER makes each row add everything up to itself.

LAG: compare with the previous row

Simply: LAG looks back at the row before the current one and gives you its value. Think of a class register that shows each student’s last score next to today’s score. PARTITION BY makes LAG stop at each group’s edge, so each order is only compared with the last order from the same restaurant.

What to know: lag(x) OVER (PARTITION BY group ORDER BY time) returns the previous row’s x inside the same group, and NULL when that group has no earlier row. ORDER BY inside OVER decides which row counts as the previous one. Only PARTITION BY restarts LAG for each group.

Example. The SQL and Drizzle are the same as on the quick page. The piles are:

  • Spice Hub (restaurant_id 1): orders 101, 104, 105, in time order.
  • Dosa Den (restaurant_id 2): order 102.

Step 1, the piles with lag(total) inside each (rows in their pile order). Each row reads the total of the row above it in its own pile:

pileordertotalprev_total (lag)
Spice Hub101700NULL (first in pile)
Spice Hub104400700
Spice Hub105250400
Dosa Den102360NULL (first in pile)

Step 2, the result with the change column (total - prev_total):

order_idrestaurant_idtotalprev_totalchange
1011700NULLNULL
1041400700-300
1051250400-150
1022360NULLNULL

Order 102 is NULL because it is the first row in its own pile. Order 101 is earlier in time, but it belongs to Spice Hub. Any subtraction with NULL is NULL, so the change is NULL too.

The wrong versions, and what they return

  • Restaurant in ORDER BY, not PARTITION BY: lag(total) OVER (ORDER BY restaurant_id, created_at) makes one pile. Nothing restarts, so each row compares with the row above it in the whole list:
order_idrestaurant_idtotalprev_total (wrong)
1011700NULL
1041400700
1051250400
1022360250

Order 102 now shows 250, which is Spice Hub’s last order. The comparison crosses restaurants, which is wrong.

  • Plain GROUP BY restaurant: you get one row per restaurant, so there is no order row left to hold a “previous” value.

Why this, not that

  • PARTITION BY restaurant_id vs restaurant_id in ORDER BY: ORDER BY decides which row counts as the previous one, but it never restarts LAG. Only PARTITION BY restarts LAG for each group. The wrong table above is the proof.
  • Window vs GROUP BY: the window keeps all four order rows. GROUP BY would keep two rows, one per restaurant, and the comparison would be lost.
  • Default value, one line: lag(total, 1, 0) returns 0 instead of NULL when there is no previous row. Order 102’s change would then be 360 - 0 = 360, which is only right if “nothing before” should count as zero.
  • LEAD, one line: lead(total) reads the next row instead. For order 101 in Spice Hub it returns 400, the total of order 104.
  • LAG needs ORDER BY: without ORDER BY, “the row before” is undefined, and the database may return them in any order.

Trigger card

When I see “previous”, “change since last” or “compared to last time”, I use lag(x) OVER (PARTITION BY group ORDER BY time), because LAG reads the row before mine and PARTITION BY restarts it for each group.

Say it in an interview

Start with the 60-second answer from the quick page. If they push deeper, add one of these:

  • Frames and ties: “With ORDER BY and no frame, the default is RANGE from the start to the current row, so tied rows get the same running total. ROWS counts each row separately instead.”
  • The LAST_VALUE trap: “LAST_VALUE usually returns the current row, because the default frame ends at the current row. To get the real last value, set the frame to ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.”
  • Cost: “Each window with PARTITION BY and ORDER BY makes the database sort rows inside each pile. On large tables that sort is the cost, so keep the window to the rows you need.”

Questions interviewers ask

The eight from the quick page, plus these harder ones. Tap to reveal.

Mental map

Window functions mental map

The same map as the quick page. Each branch is a section above.

Watch

Alex The Analyst, about 4 minutes: “Intermediate SQL Tutorial | Partition By”. It covers PARTITION BY, the per-group part of OVER. It does not cover rank, running totals or LAG.

Data with Baraa, about 64 minutes: “SQL Ranking Window Functions | ROW_NUMBER, RANK, DENSE_RANK, NTILE”. A longer run through the ranking functions. It does not cover running totals or LAG.