SQL course · Window functions lesson

SQL Window Functions Explained with Interview Examples

Learn ROW_NUMBER, RANK and LAG with four runnable PostgreSQL exercises, expected outputs and month-over-month revenue reasoning.

Original PostgreSQL examples · Learn the method, test the output, explain the result.

SQL LEARNING PREVIEW
Window functions lessonPostgreSQL

Core idea

A window calculation preserves the row it annotates.

LAG(revenue) OVER
(ORDER BY month)
→ previous month
First understand the query.Then try the next variation without copying the answer.

The direct answer

Compute across related rows without collapsing them.

A window function computes a value using rows related to the current row while keeping a result row for each input row. That makes it useful for month-over-month changes, ranking within a region and comparing an event to a previous event. A grouped aggregate, by contrast, reduces many input rows to one result row per group.

This lesson gives four runnable PostgreSQL exercises with expected output. Start with month-over-month revenue, then use ROW_NUMBER, RANK and LAG. If grouping still feels uncertain, review the aggregation method first. Course options follow this overview.

Course access

Choose your next step in SQL.

Review the current course options and access details here.

Heycademy Courses · Coming Soon

Master SQL with Heycademy

We’re preparing an interactive learning experience with practical exercises, skill assessments and personalized learning to help you build confidence and master new skills.

Launching soon!
We’re putting the finishing touches on this course. Please check back for updates.

Core terms

Partition, order and frame are different choices.

OVER (...) marks a window calculation. PARTITION BY divides rows into independent groups for that calculation. ORDER BY inside the window sets the sequence used by ranking and LAG. A frame limits which rows an aggregate window considers; it matters especially for running totals. Do not confuse the window’s ORDER BY with the final query ORDER BY that controls display order.

The PostgreSQL window tutorial explains row preservation and partition behavior. The official window function reference defines ROW_NUMBER, RANK and LAG. The following examples use short data so you can predict each output by hand.

Exercise 1 · LAG

Month-over-month revenue from a complete month table.

monthly_revenue
monthrevenue
2026-01100
2026-02130
2026-0390
CREATE TEMP TABLE monthly_revenue (month text PRIMARY KEY, revenue integer);
INSERT INTO monthly_revenue VALUES ('2026-01',100),('2026-02',130),('2026-03',90);
WITH changes AS (
  SELECT month, revenue,
         LAG(revenue) OVER (ORDER BY month) AS previous_revenue
  FROM monthly_revenue
)
SELECT month, revenue, previous_revenue,
       revenue - previous_revenue AS change
FROM changes ORDER BY month;
Expected month-over-month output
monthrevenuepreviouschange
2026-01100NULLNULL
2026-0213010030
2026-0390130-40

The first month has no preceding row, so LAG returns NULL and the subtraction is NULL. February rises by 30; March falls by 40. This table includes consecutive months. If a month is missing, LAG compares with the previous available row, not necessarily the previous calendar month; build a calendar series if the business question requires every calendar month.

Exercise 2 · ROW_NUMBER

Choose one latest event per user.

CREATE TEMP TABLE events (event_id integer PRIMARY KEY, user_id text, event_date text);
INSERT INTO events VALUES (1,'Ada','2026-02-01'),(2,'Ada','2026-02-03'),
                          (3,'Ben','2026-02-02'),(4,'Ben','2026-02-02');
WITH numbered AS (
  SELECT user_id,event_id,event_date,
         ROW_NUMBER() OVER (PARTITION BY user_id
                            ORDER BY event_date DESC,event_id DESC) AS rn
  FROM events
)
SELECT user_id,event_id,event_date FROM numbered WHERE rn=1 ORDER BY user_id;
Expected latest event
userevent idevent date
Ada22026-02-03
Ben42026-02-02

Ben’s two events tie on date. Event id breaks the tie, making event 4 the chosen row. Without that second ordering rule, the “latest” choice among equal dates is not determined by the task.

Keep building this skill

Apply the method on fresh SQL problems.

The course options are above. Return to the synced pricing block whenever you are ready.

Explore course options →

Exercise 3 · RANK

Keep tied positions visible.

CREATE TEMP TABLE scores (name text PRIMARY KEY, score integer);
INSERT INTO scores VALUES ('Ada',95),('Ben',90),('Cleo',90),('Dina',80);
SELECT name,score,RANK() OVER (ORDER BY score DESC) AS place
FROM scores ORDER BY score DESC,name;
Expected ranks
namescoreplace
Ada951
Ben902
Cleo902
Dina804

RANK gives Ben and Cleo the same place and skips third. ROW_NUMBER would number them separately; DENSE_RANK would put Dina in third. Ask whether the requirement wants exactly N rows or every tied row before choosing a ranking function.

Exercise 4 · partitioned LAG

Compare each team with its own previous result.

CREATE TEMP TABLE team_sales (team text, month text, revenue integer,
  PRIMARY KEY(team,month));
INSERT INTO team_sales VALUES ('A','2026-01',50),('A','2026-02',70),
                              ('B','2026-01',80),('B','2026-02',75);
SELECT team,month,revenue,
       LAG(revenue) OVER (PARTITION BY team ORDER BY month) AS previous
FROM team_sales ORDER BY team,month;
Expected partitioned comparison
teammonthrevenueprevious
A2026-0150NULL
A2026-027050
B2026-0180NULL
B2026-027580

Partitioning resets the comparison at the start of team B. Without it, B’s January value might be compared with A’s February value, which answers a different question.

Unseen check

Change one input, predict one row.

Add team A’s March revenue of 65. The new row’s previous value should be 70. The other four rows should retain their previous values. Add a third Ben event on a later date; the latest-event query should select it. Each variation tests whether you understood the window definition rather than copied a fixed answer.

Show the explanation

The partitioned LAG for A in March sees A February immediately before it, so previous = 70. A new later Ben event receives ROW_NUMBER 1 within Ben’s partition because the window order is event_date DESC, then event_id DESC.

When an answer is wrong, inspect three things in order: input rows, partition key, and ordering rule. Then inspect any final WHERE filter. The 20-question set includes a top-three-per-region example that combines aggregation and ROW_NUMBER.

Bonus window pattern

A running total needs an explicit frame.

On the three-month revenue table, a running total should be 100 in January, 230 in February and 320 in March. Use an aggregate window ordered by month. The explicit ROWS frame says to include every row from the start through the current row; it also makes your intent clearer when duplicate ordering values may exist.

SELECT month,revenue,
       SUM(revenue) OVER (
         ORDER BY month
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS running_total
FROM monthly_revenue ORDER BY month;
Expected running total
monthrevenuerunning total
2026-01100100
2026-02130230
2026-0390320

Do not add these running totals together to calculate overall revenue: that would count January several times. The last running total is the overall sum for this ordered set, while each preceding row is a partial accumulation. If the task is “total revenue per month,” use GROUP BY before the window when the source contains individual orders.

FAQ

Questions about this skill.

Does a window function always keep the same number of rows?

The window calculation itself annotates input rows. A later WHERE filter or outer query can reduce the displayed rows.

Why is the first LAG value NULL?

There is no preceding row in that ordered partition unless a default is supplied.

What should I do when two rows tie?

State the business tie rule. Add a deterministic secondary ordering column when exactly one row must be chosen.

Continue with the SQL course

Make this skill reliable on new data.

Return to the course options and choose the next learning step.

Take the next step →
Scroll to Top