Window Functions: Partitions, Order and Frames
How a window function keeps every row while it computes over related rows: PARTITION BY, ORDER BY and the frame, the three ranking functions, LAG and LEAD, and the default frame that surprises most people.
Contentsand lesson path
On this page
- Why it matters
- Set up a small sales table
- The OVER clause: partition first, then order
- Ranking: ROW_NUMBER, RANK and DENSE_RANK
- Looking at neighbours: LAG, LEAD, FIRST_VALUE and LAST_VALUE
- Frames: which rows a running or moving aggregate reads
- Check your understanding
- Apply it
- Review prompt
Lessons of Advanced SQL
- Window Functions: Partitions, Order and Frames Concept · 25 min
- Lab: Retention, Running Totals and Gaps-and-Islands Lab · 30 min
- Readable Step-by-Step Queries with CTEs and Recursion Worked example · 25 min
- Multi-Level Reports, Pivots and Result-Set Comparisons Lab · 25 min
- Deduplicate, MERGE and Package the Load as a Procedure Lab · 30 min
- Check: Analytical Query Challenge Knowledge check · 8 questions
What you will learn
- Compute rankings, running totals, period-over-period changes and moving averages with window functions and explicit frames.
Prerequisites: SQL Fundamentals
01. Why it matters
Suppose a manager asks: "For every sale, what share of its region's revenue did it bring in?" With GROUP BY region you get one row per region and lose the individual sales. You could compute the totals in a subquery and join them back, but that grows quickly once the next question is "and rank each sale inside its region".
A window function solves this kind of question directly. It computes a value over a set of rows that are related to the current row, called its window, and it returns one value for every input row. Rows are not collapsed. Rankings, running totals, period-over-period changes and moving averages are all built this way. Window functions are standard SQL and work, with small differences, in most analytical databases.
This lesson uses PostgreSQL 17 and builds on SQL Fundamentals, especially GROUP BY.
02. Set up a small sales table
Every query in this lesson runs as shown. Start PostgreSQL 17 in Docker. If you still have the sql-lab container from SQL Fundamentals, run docker start sql-lab instead. Save the script below as setup.sql: it creates eight sales by four sales reps in two regions. Notice two details that matter later: some amounts are tied, and no sale happened on 5 March.
docker run --name sql-lab -e POSTGRES_PASSWORD=learnsql -d postgres:17-alpineCREATE TABLE sales (
id int PRIMARY KEY,
region text NOT NULL,
rep text NOT NULL,
sale_date date NOT NULL,
amount numeric(8,2) NOT NULL
);
INSERT INTO sales VALUES
(1, 'north', 'ana', '2026-03-02', 120),
(2, 'north', 'ana', '2026-03-03', 80),
(3, 'north', 'ben', '2026-03-03', 200),
(4, 'north', 'ben', '2026-03-06', 80),
(5, 'south', 'cai', '2026-03-02', 150),
(6, 'south', 'cai', '2026-03-04', 150),
(7, 'south', 'dee', '2026-03-04', 90),
(8, 'south', 'dee', '2026-03-07', 60);
SELECT count(*) AS sales FROM sales;docker exec sql-lab psql -U postgres -X -q -c "SET client_min_messages = warning" \
-c "DROP DATABASE IF EXISTS win" -c "CREATE DATABASE win"
docker exec -i sql-lab psql -U postgres -d win -X -q < setup.sql sales
-------
8
(1 row)Open a session with docker exec -it sql-lab psql -U postgres -d win and paste the queries that follow. The -q flag only hides messages such as CREATE TABLE.
03. The OVER clause: partition first, then order
Start with the grouped version, so you can see what is lost.
SELECT region, sum(amount) AS region_total
FROM sales GROUP BY region ORDER BY region; region | region_total
--------+--------------
north | 480.00
south | 450.00
(2 rows)Now write the same sum as a window function. The OVER (...) clause turns an ordinary aggregate such as sum into a window function. Inside it, PARTITION BY region splits the rows into groups, much like GROUP BY, but each row stays in the result and simply sees the other rows of its partition. That is why every north row can show the north total next to its own amount, and why the percentage needs no join.
SELECT id, region, amount,
sum(amount) OVER (PARTITION BY region) AS region_total,
round(100 * amount / sum(amount) OVER (PARTITION BY region), 1) AS pct
FROM sales ORDER BY id; id | region | amount | region_total | pct
----+--------+--------+--------------+------
1 | north | 120.00 | 480.00 | 25.0
2 | north | 80.00 | 480.00 | 16.7
3 | north | 200.00 | 480.00 | 41.7
4 | north | 80.00 | 480.00 | 16.7
5 | south | 150.00 | 450.00 | 33.3
6 | south | 150.00 | 450.00 | 33.3
7 | south | 90.00 | 450.00 | 20.0
8 | south | 60.00 | 450.00 | 13.3
(8 rows)A full window specification has three optional parts, always in this order: PARTITION BY (which rows belong together), ORDER BY (the order of rows inside each partition) and a frame (which rows around the current one the function reads). Leave out PARTITION BY and the whole result is one partition. The rest of this lesson adds the other two parts one at a time.
It also helps to know when window functions run. PostgreSQL evaluates a query in this logical order: FROM and joins, WHERE, GROUP BY, HAVING, then window functions, then the final ORDER BY and LIMIT. Two consequences follow. A window function can read grouped results, so sum(sum(amount)) OVER () is legal after a GROUP BY. And WHERE runs too early to see a window result, so you cannot filter on one there.
SELECT id, region FROM sales
WHERE rank() OVER (ORDER BY amount DESC) = 1;ERROR: window functions are not allowed in WHERE
LINE 2: WHERE rank() OVER (ORDER BY amount DESC) = 1;
^The fix is to compute the window value in a common table expression (CTE, a named subquery introduced by WITH) or a subquery, and filter in the outer query, which runs after the window has been computed. Lesson 3 covers CTEs in depth.
WITH ranked AS (
SELECT id, region, amount,
rank() OVER (PARTITION BY region ORDER BY amount DESC) AS rnk
FROM sales
)
SELECT id, region, amount FROM ranked WHERE rnk = 1 ORDER BY region, id; id | region | amount
----+--------+--------
3 | north | 200.00
5 | south | 150.00
6 | south | 150.00
(3 rows)04. Ranking: ROW_NUMBER, RANK and DENSE_RANK
The three ranking functions differ only in how they treat ties, rows whose ORDER BY values are equal. The query below ranks sales inside each region from the largest amount down. The WINDOW w AS (...) clause names a window once so that several functions can share it.
SELECT region, amount,
row_number() OVER w AS row_number,
rank() OVER w AS rank,
dense_rank() OVER w AS dense_rank
FROM sales
WINDOW w AS (PARTITION BY region ORDER BY amount DESC)
ORDER BY region, amount DESC, id; region | amount | row_number | rank | dense_rank
--------+--------+------------+------+------------
north | 200.00 | 1 | 1 | 1
north | 120.00 | 2 | 2 | 2
north | 80.00 | 3 | 3 | 3
north | 80.00 | 4 | 3 | 3
south | 150.00 | 1 | 1 | 1
south | 150.00 | 2 | 1 | 1
south | 90.00 | 3 | 3 | 2
south | 60.00 | 4 | 4 | 3
(8 rows)Read the south rows. The two sales of 150 tie. row_number still gives them 1 and 2, because it numbers rows without exception. rank gives both 1 and then jumps to 3, like a sports table where two runners share first place and nobody is second. dense_rank gives both 1 and continues with 2, so it counts distinct values.
Choose by the question you are answering:
row_numberwhen you need exactly one row per group, such as the latest record per customer. Add a unique tie-breaker to itsORDER BY(hereamount DESC, id), otherwise PostgreSQL may order tied rows differently on the next run and pick a different winner.rankfor competition-style positions, where a tie should push the next row down.dense_rankfor "the top three amounts", where several rows may share each amount.
05. Looking at neighbours: LAG, LEAD, FIRST_VALUE and LAST_VALUE
lag(x) returns x from the previous row of the partition, in window order; lead(x) returns it from the next row. They are how you compute period-over-period change: subtract the previous value from the current one. Both take an optional offset and a default, as in lag(amount, 1, 0), for the case where no such row exists.
SELECT rep, sale_date, amount,
lag(amount) OVER w AS prev_amount,
amount - lag(amount) OVER w AS change,
lead(sale_date) OVER w AS next_sale
FROM sales
WINDOW w AS (PARTITION BY rep ORDER BY sale_date)
ORDER BY rep, sale_date; rep | sale_date | amount | prev_amount | change | next_sale
-----+------------+--------+-------------+---------+------------
ana | 2026-03-02 | 120.00 | | | 2026-03-03
ana | 2026-03-03 | 80.00 | 120.00 | -40.00 |
ben | 2026-03-03 | 200.00 | | | 2026-03-06
ben | 2026-03-06 | 80.00 | 200.00 | -120.00 |
cai | 2026-03-02 | 150.00 | | | 2026-03-04
cai | 2026-03-04 | 150.00 | 150.00 | 0.00 |
dee | 2026-03-04 | 90.00 | | | 2026-03-07
dee | 2026-03-07 | 60.00 | 90.00 | -30.00 |
(8 rows)The first sale of each rep has no previous row, so prev_amount is NULL, and so is change, because arithmetic with NULL gives NULL. That is usually what you want: "no previous period" is not the same as "a previous period of zero". Pass a default only when a missing row really means zero.
first_value(x) and last_value(x) look different but hide a trap. They read the first and last rows of the frame, not of the partition, and the default frame stops at the current row. Compare the two last_value columns below.
SELECT id, region, sale_date, amount,
first_value(amount) OVER w AS first_amt,
last_value(amount) OVER w AS last_amt_default,
last_value(amount) OVER (w ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING) AS last_amt_full
FROM sales
WINDOW w AS (PARTITION BY region ORDER BY sale_date, id)
ORDER BY region, sale_date, id; id | region | sale_date | amount | first_amt | last_amt_default | last_amt_full
----+--------+------------+--------+-----------+------------------+---------------
1 | north | 2026-03-02 | 120.00 | 120.00 | 120.00 | 80.00
2 | north | 2026-03-03 | 80.00 | 120.00 | 80.00 | 80.00
3 | north | 2026-03-03 | 200.00 | 120.00 | 200.00 | 80.00
4 | north | 2026-03-06 | 80.00 | 120.00 | 80.00 | 80.00
5 | south | 2026-03-02 | 150.00 | 150.00 | 150.00 | 60.00
6 | south | 2026-03-04 | 150.00 | 150.00 | 150.00 | 60.00
7 | south | 2026-03-04 | 90.00 | 150.00 | 90.00 | 60.00
8 | south | 2026-03-07 | 60.00 | 150.00 | 60.00 | 60.00
(8 rows)With the default frame, last_amt_default just repeats the current amount, because the frame ends at the current row. Extending the frame to UNBOUNDED FOLLOWING gives the real last sale of the region. first_value works with the default frame because that frame starts at the first row of the partition.
06. Frames: which rows a running or moving aggregate reads
A frame is the slice of the partition, around the current row, that an aggregate or a value function such as last_value reads. Ranking functions and lag/lead ignore it. You write it as a mode followed by a start and an end, for example ROWS BETWEEN 2 PRECEDING AND CURRENT ROW. There are three modes:
ROWScounts physical rows: "2 PRECEDING" means the two rows before this one.RANGEworks on theORDER BYvalue: "INTERVAL '2 days' PRECEDING" means every row whose date is at most two days earlier. Rows with the same value, called peers, are always in or out together.GROUPScounts groups of peers: "1 PRECEDING" means the previous set of tied rows.
If you write ORDER BY without a frame, PostgreSQL uses RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. "Current row" in RANGE mode includes all peers of the current row, so tied rows share one running total. Without ORDER BY, the frame is the whole partition, which is why the region total earlier was the same on every row. The query below shows the difference on the north sales, where two sales fall on 3 March.
SELECT id, sale_date, amount,
sum(amount) OVER (ORDER BY sale_date) AS range_total,
sum(amount) OVER (ORDER BY sale_date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS rows_total
FROM sales WHERE region = 'north'
ORDER BY sale_date, id; id | sale_date | amount | range_total | rows_total
----+------------+--------+-------------+------------
1 | 2026-03-02 | 120.00 | 120.00 | 120.00
2 | 2026-03-03 | 80.00 | 400.00 | 200.00
3 | 2026-03-03 | 200.00 | 400.00 | 400.00
4 | 2026-03-06 | 80.00 | 480.00 | 480.00
(4 rows)Rows 2 and 3 are peers on sale_date, so range_total shows 400 on both. The ROWS version with id as a tie-breaker adds one row at a time. Neither is wrong: a daily total wants peers together, a row-by-row ledger wants ROWS. The risk is getting the default without noticing.
Moving averages raise a second question: is "the last three" three rows or three days? The query first sums revenue per day. There are no sales on 5 March, so that day has no row at all.
WITH daily AS (
SELECT sale_date, sum(amount) AS revenue FROM sales GROUP BY sale_date
)
SELECT sale_date, revenue,
round(avg(revenue) OVER (ORDER BY sale_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS avg_3_rows,
round(avg(revenue) OVER (ORDER BY sale_date
RANGE BETWEEN INTERVAL '2 days' PRECEDING AND CURRENT ROW), 2)
AS avg_3_days_with_rows
FROM daily ORDER BY sale_date; sale_date | revenue | avg_3_rows | avg_3_days_with_rows
------------+---------+------------+----------------------
2026-03-02 | 270.00 | 270.00 | 270.00
2026-03-03 | 280.00 | 275.00 | 275.00
2026-03-04 | 240.00 | 263.33 | 263.33
2026-03-06 | 80.00 | 200.00 | 160.00
2026-03-07 | 60.00 | 126.67 | 70.00
(5 rows)On 6 March the ROWS frame reads 3, 4 and 6 March: three rows, but four calendar days. The RANGE frame reads only 4 and 6 March, because those are the rows within two days, and averages two values. If the business question is "average revenue per calendar day over the last three days", both are wrong, because a day without sales should count as zero. The reliable fix is to build a calendar, one row per day from generate_series, and left-join the data to it, so every day exists before the window runs.
WITH calendar AS (
SELECT d::date AS sale_date
FROM generate_series(date '2026-03-02', date '2026-03-07',
interval '1 day') AS d
), daily AS (
SELECT c.sale_date, coalesce(sum(s.amount), 0) AS revenue
FROM calendar c LEFT JOIN sales s ON s.sale_date = c.sale_date
GROUP BY c.sale_date
)
SELECT sale_date, revenue,
round(avg(revenue) OVER (ORDER BY sale_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS avg_3_days
FROM daily ORDER BY sale_date; sale_date | revenue | avg_3_days
------------+---------+------------
2026-03-02 | 270.00 | 270.00
2026-03-03 | 280.00 | 275.00
2026-03-04 | 240.00 | 263.33
2026-03-05 | 0 | 173.33
2026-03-06 | 80.00 | 106.67
2026-03-07 | 60.00 | 46.67
(6 rows)Now 5 March appears with zero revenue, and every average covers exactly three days. The first two rows have shorter frames because there is no earlier data; report them, hide them or start the calendar earlier, but decide on purpose. You will use the same calendar pattern for a 7-day moving average in the lab.
07. Check your understanding
08. Apply it
The practice project for this skill asks for SQL over an orders-and-events dataset. Start the window-function part now, on the sales table or on your own data:
- Write a query that returns daily revenue and the change from the previous day with
lag. Decide what the first day should show and say why. - Return each rep's first and latest sale on every row, once with
first_value/last_valueand an explicit frame, and once withrow_numberin a CTE. - Build a calendar with
generate_seriesand compute a 3-day moving average that counts days without sales as zero. Check one row by hand.
09. Review prompt
Without looking back, answer these in a few sentences each:
- What does
PARTITION BYdo thatGROUP BYdoes not? - Why can a window function not appear in
WHERE, and where do you filter on it instead? - Given the values 10, 10, 7, what do
row_number,rankanddense_rankreturn? - What frame does PostgreSQL use when a window has
ORDER BYbut no frame clause, and which two functions does that default most often surprise? - When is a
ROWSframe of "6 preceding" not the same as "the last seven days"?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.