SQL Window Functions Explained With Examples
What a SQL window function is and how OVER, PARTITION BY, ORDER BY, and frames work, with ranking, running totals, top N per group, and gap-filling run on PostgreSQL 16.
On this page · 15 sections
- The sample data
- The OVER clause: PARTITION BY, ORDER BY, and the frame
- ROW_NUMBER, RANK, and DENSE_RANK on tied values
- Running totals, moving averages, and the default frame
- LAG and LEAD: the previous and next row
- FIRST_VALUE, LAST_VALUE, and the frame
- Where window functions run, and top N per group
- Gap-filling time series with window functions
- Window function reference
- Frequently Asked Questions
- What are the types of window functions in SQL?
- How do you create a running total with a SQL window function?
- When should you use a window function instead of GROUP BY?
- What is the difference between ROW_NUMBER, RANK, and DENSE_RANK?
- Primary sources and further reading
- Topic
- SQL for Analytics Engineers
- Category
- SQL
- Reading path
- Then: Model subscription changes
A SQL window function calculates a value for each row from a set of rows related to that row, without merging those rows into one the way GROUP BY does. The OVER clause after the function defines the set: PARTITION BY splits the rows into groups, ORDER BY sorts each group, and a frame limits the calculation to rows around the current one. SQL window functions rank rows, keep running totals and moving averages, and compare a row with its neighbors.
The sample data
The examples use one table of seven orders and were run on PostgreSQL 16. Two kinds of ties matter later: orders 2 and 4 have the same amount (as do 3 and 7), and orders 4 and 6 have the same region and date.
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
region TEXT NOT NULL,
order_date DATE NOT NULL,
amount INTEGER NOT NULL
);
INSERT INTO orders VALUES
(1, 'East', '2026-03-02', 120),
(2, 'East', '2026-03-03', 200),
(3, 'West', '2026-03-03', 150),
(4, 'East', '2026-03-05', 200),
(5, 'West', '2026-03-05', 80),
(6, 'East', '2026-03-05', 90),
(7, 'West', '2026-03-08', 150);
The OVER clause: PARTITION BY, ORDER BY, and the frame
A function call becomes a window function call when OVER follows it. OVER takes three optional parts:
- PARTITION BY divides the rows into partitions, and the function is computed separately in each. Without it, all rows are one partition.
- ORDER BY sets the order in which the function processes a partition's rows. It is separate from the query's ORDER BY, which sorts the output.
- A frame clause, such as
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW, narrows the calculation to part of the partition, the window frame, for the functions that use one.
SELECT
order_id,
region,
amount,
SUM(amount) OVER () AS all_orders,
SUM(amount) OVER (PARTITION BY region) AS region_total
FROM orders
ORDER BY order_id;
order_id | region | amount | all_orders | region_total
----------+--------+--------+------------+--------------
1 | East | 120 | 990 | 610
2 | East | 200 | 990 | 610
3 | West | 150 | 990 | 380
4 | East | 200 | 990 | 610
5 | West | 80 | 990 | 380
6 | East | 90 | 990 | 610
7 | West | 150 | 990 | 380
(7 rows)
All seven rows remain. OVER () is one partition, so every row gets the total, 990, and PARTITION BY region gives each row its region's total. GROUP BY would return two rows, one per region.
ROW_NUMBER, RANK, and DENSE_RANK on tied values
The three ranking functions number each partition's rows in the window's ORDER BY order. They differ only for rows with equal ORDER BY values, which PostgreSQL calls peers.
SELECT
region,
order_id,
amount,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC, order_id) AS row_num,
RANK() OVER (PARTITION BY region ORDER BY amount DESC) AS rnk,
DENSE_RANK() OVER (PARTITION BY region ORDER BY amount DESC) AS dense_rnk
FROM orders
ORDER BY region, row_num;
region | order_id | amount | row_num | rnk | dense_rnk
--------+----------+--------+---------+-----+-----------
East | 2 | 200 | 1 | 1 | 1
East | 4 | 200 | 2 | 1 | 1
East | 1 | 120 | 3 | 3 | 2
East | 6 | 90 | 4 | 4 | 3
West | 3 | 150 | 1 | 1 | 1
West | 7 | 150 | 2 | 1 | 1
West | 5 | 80 | 3 | 3 | 2
(7 rows)
ROW_NUMBER gives every row a different number. RANK gives peers the same number and leaves a gap after them: 1, 1, 3. DENSE_RANK leaves no gap: 1, 1, 2. ROW_NUMBER sorts by order_id as well because, without a tiebreaker, the database may number tied rows in either order.
Running totals, moving averages, and the default frame
An aggregate with ORDER BY in its window becomes cumulative because of the default frame. With ORDER BY and no frame clause, PostgreSQL uses RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: from the start of the partition through the current row and all of its peers. With no ORDER BY, the frame is the whole partition. This query totals the East orders both ways and adds a three-order moving average:
SELECT
order_id,
order_date,
amount,
SUM(amount) OVER (ORDER BY order_date) AS default_frame,
SUM(amount) OVER (
ORDER BY order_date, order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total,
ROUND(AVG(amount) OVER (
ORDER BY order_date, order_id
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
), 2) AS moving_avg_3
FROM orders
WHERE region = 'East'
ORDER BY order_date, order_id;
order_id | order_date | amount | default_frame | running_total | moving_avg_3
----------+------------+--------+---------------+---------------+--------------
1 | 2026-03-02 | 120 | 120 | 120 | 120.00
2 | 2026-03-03 | 200 | 320 | 320 | 160.00
4 | 2026-03-05 | 200 | 610 | 520 | 173.33
6 | 2026-03-05 | 90 | 610 | 610 | 163.33
(4 rows)
Orders 4 and 6 have the same date, so under the default frame they are peers and both show 610, where order 4 should show 520. The running_total column fixes it in two steps: order_id makes the ordering unique, and ROWS ends the frame at the current row, not at its last peer. Do both: PostgreSQL's documentation warns that ROWS is unpredictable when the ordering is not unique.
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW averages the current order and up to two before it: 173.33 is the average of 120, 200, and 200.
LAG and LEAD: the previous and next row
LAG returns a value from an earlier row of the partition and LEAD from a later one, one row away by default.
SELECT
order_id,
order_date,
amount,
LAG(amount) OVER (ORDER BY order_date) AS previous_amount,
LEAD(amount) OVER (ORDER BY order_date) AS next_amount
FROM orders
WHERE region = 'West'
ORDER BY order_date;
order_id | order_date | amount | previous_amount | next_amount
----------+------------+--------+-----------------+-------------
3 | 2026-03-03 | 150 | | 80
5 | 2026-03-05 | 80 | 150 | 150
7 | 2026-03-08 | 150 | 80 |
(3 rows)
The first row has no previous row and the last has no next, so those cells are NULL, which psql prints as empty. A third argument replaces the NULL: LAG(amount, 1, 0) returns 0 for order 3. For more, see LAG and LEAD in SQL.
FIRST_VALUE, LAST_VALUE, and the frame
FIRST_VALUE and LAST_VALUE read the first and last row of the window frame, not of the partition. The default frame ends at the current row or its last peer, so LAST_VALUE returns the row's own value:
SELECT
order_id,
amount,
FIRST_VALUE(amount) OVER (ORDER BY order_date, order_id) AS first_amount,
LAST_VALUE(amount) OVER (ORDER BY order_date, order_id) AS last_default,
LAST_VALUE(amount) OVER (
ORDER BY order_date, order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_amount
FROM orders
WHERE region = 'East'
ORDER BY order_date, order_id;
order_id | amount | first_amount | last_default | last_amount
----------+--------+--------------+--------------+-------------
1 | 120 | 120 | 120 | 90
2 | 200 | 120 | 200 | 90
4 | 200 | 120 | 200 | 90
6 | 90 | 120 | 90 | 90
(4 rows)
last_default repeats amount. Extending the frame to UNBOUNDED FOLLOWING returns 90, the last East order's amount, on every row. FIRST_VALUE is safe because the default frame starts at the partition's first row.
Where window functions run, and top N per group
PostgreSQL evaluates window functions after WHERE, GROUP BY, and HAVING. They see only the rows that pass those clauses (the East queries never saw a West order), and they are allowed only in the SELECT list and the query's ORDER BY. Filtering on one in WHERE fails:
SELECT order_id
FROM orders
WHERE ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) <= 2;
ERROR: window functions are not allowed in WHERE
LINE 3: WHERE ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount...
^
A column alias for the window function fails there too. Compute the window function in a subquery or a common table expression and filter outside it. This is the top N per group pattern, here the two largest orders per region:
SELECT region, order_id, amount
FROM (
SELECT
region,
order_id,
amount,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC, order_id) AS row_num
FROM orders
) AS ranked
WHERE row_num <= 2
ORDER BY region, row_num;
region | order_id | amount
--------+----------+--------
East | 2 | 200
East | 4 | 200
West | 3 | 150
West | 7 | 150
(4 rows)
ROW_NUMBER returns at most N rows per group: row_num = 1 returns orders 2 and 3. Rank with RANK and filter on 1, and all four tied orders come back. Snowflake and BigQuery have a QUALIFY clause that filters on a window function without the subquery. PostgreSQL 16 does not. See the SQL QUALIFY clause.
Because grouping happens first (see HAVING vs. WHERE), a window function in a GROUP BY query sees one row per group and can take an aggregate as its argument: grouped by region, SUM(SUM(amount)) OVER () returns 990 on both rows.
Gap-filling time series with window functions
Time series from real systems skip days: a job did not run, a sensor was offline, nothing was sold. Window functions handle both halves of the problem: LAG finds the gaps, and a running COUNT carries the last known value forward once a date spine, a generated row for every day, has filled in the missing days.
CREATE TEMP TABLE daily_stock (
day DATE PRIMARY KEY,
units_on_hand INTEGER
);
INSERT INTO daily_stock VALUES
(DATE '2026-03-01', 40),
(DATE '2026-03-02', 35),
(DATE '2026-03-05', 60),
(DATE '2026-03-06', NULL),
(DATE '2026-03-07', 52);
Find the gaps by comparing each recorded day with the one before it:
WITH ordered AS (
SELECT day, LAG(day) OVER (ORDER BY day) AS previous_day
FROM daily_stock
)
SELECT previous_day, day, day - previous_day - 1 AS missing_days
FROM ordered
WHERE day - previous_day > 1;
previous_day | day | missing_days
--------------+------------+--------------
2026-03-02 | 2026-03-05 | 2
(1 row)
Fill the gaps by generating every day, left-joining the data, and forward-filling:
WITH spine AS (
SELECT CAST(d AS DATE) AS day
FROM generate_series(DATE '2026-03-01', DATE '2026-03-07', INTERVAL '1 day') AS d
),
grouped AS (
SELECT
s.day,
t.units_on_hand,
COUNT(t.units_on_hand) OVER (ORDER BY s.day) AS fill_group
FROM spine AS s
LEFT JOIN daily_stock AS t ON t.day = s.day
)
SELECT
day,
units_on_hand,
MAX(units_on_hand) OVER (PARTITION BY fill_group) AS units_forward_filled
FROM grouped
ORDER BY day;
day | units_on_hand | units_forward_filled
------------+---------------+----------------------
2026-03-01 | 40 | 40
2026-03-02 | 35 | 35
2026-03-03 | | 35
2026-03-04 | | 35
2026-03-05 | 60 | 60
2026-03-06 | | 60
2026-03-07 | 52 | 52
(7 rows)
COUNT(units_on_hand) skips NULLs, so the running count rises only on days with a value. Every missing day therefore shares a fill_group with the last known day, and MAX over that group returns the value to carry forward. PostgreSQL does not implement the SQL standard's IGNORE NULLS option, so LAST_VALUE cannot skip the NULLs there.
Forward-fill levels such as stock on hand or account balances. For counts, such as orders per day, a missing day usually means zero, so use COALESCE(orders, 0) instead. In dbt, use a date spine model.
Window function reference
A frame clause, or the default frame, affects only the functions that read the frame.
| Function | Returns | Reads the frame |
|---|---|---|
ROW_NUMBER() | Row number within the partition, from 1 | No |
RANK() | Rank, with gaps after ties | No |
DENSE_RANK() | Rank, without gaps | No |
PERCENT_RANK() | (rank - 1) / (partition rows - 1) | No |
CUME_DIST() | Share of partition rows up to and including the row's peers | No |
NTILE(n) | Bucket number from 1 to n | No |
LAG(value, offset, default), LEAD(value, offset, default) | Value from offset rows earlier (LAG) or later (LEAD) | No |
FIRST_VALUE(value), LAST_VALUE(value) | Value from the first or last row of the frame | Yes |
NTH_VALUE(value, n) | Value from the nth row of the frame | Yes |
SUM, AVG, COUNT, MIN, MAX with OVER | Aggregate of the rows in the frame | Yes |
This guide is step 04 of the SQL hub's learning path. To write these queries yourself, try the practice exercises.
Frequently Asked Questions
What are the types of window functions in SQL?
They are usually grouped into three kinds. Ranking functions (ROW_NUMBER, RANK, DENSE_RANK, NTILE, PERCENT_RANK, CUME_DIST) number or position rows. Value functions (LAG, LEAD, FIRST_VALUE, LAST_VALUE, NTH_VALUE) return a value from another row. Aggregates such as SUM, AVG, and COUNT become window functions when OVER follows them.
How do you create a running total with a SQL window function?
Use SUM with ORDER BY in the window: SUM(amount) OVER (ORDER BY order_date, order_id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). Add PARTITION BY to restart the total for each group, and make the ordering unique so tied rows do not share a total.
When should you use a window function instead of GROUP BY?
Use GROUP BY when the result should have one row per group. Use a window function when every row must stay in the result with a rank, a running total, a group total, or a neighboring row's value beside it.
What is the difference between ROW_NUMBER, RANK, and DENSE_RANK?
They differ on ties. ROW_NUMBER gives tied rows different numbers. RANK gives them the same number and skips the next, as in 1, 1, 3. DENSE_RANK does not skip, as in 1, 1, 2.
Primary sources and further reading
- Window functions (tutorial). The definition, the default frame, evaluation after WHERE, GROUP BY, and HAVING, filtering through a subquery.
- Window function calls.
OVERsyntax, frame modes, the default frame. - Window functions (reference). What each function returns, peers, the
LAST_VALUEnote,IGNORE NULLS. - SELECT. The warning about
ROWSwith a non-unique ordering. - Table expressions. Evaluation after grouping and HAVING.
- Aggregate functions and set returning functions. NULL handling in
COUNTandMAX,generate_series. - QUALIFY, Snowflake documentation, and query syntax, BigQuery documentation. The
QUALIFYclause.
The SQL was run on PostgreSQL 16, and the output shown is what psql printed. The first six sources are PostgreSQL 16 documentation pages, read in November 2026.
- SQL
SQL QUALIFY Clause: Filter Window Functions Without Subqueries
QUALIFY lets you filter window-function outputs inline, avoiding extra subqueries and CTEs. Learn syntax, patterns, performance tips, and cross-database equivalents.
- SQL
Learn SQL: Introduction to SQL with a No‑Fluff 4‑Week Plan
A practitioner’s 4‑week plan to learn SQL for data analytics. Daily graded practice, concrete milestones, and realistic examples—no fluff, just queries.
- SQL
LAG and LEAD in SQL: Compare Each Row With the One Before or After
A practitioner’s guide to SQL LAG and LEAD for period-over-period analysis, churn flags, and sessionization—plus syntax, pitfalls, and performance tips.
