Sub topic 3
Controlling the frame: ROWS, RANGE and GROUPS
This chapter assumes you know OVER, PARTITION BY, and ORDER BY inside a window. It also assumes your database supports frame clauses, such as PostgreSQL, MySQL 8+, SQL Server, SQLite 3.25+, or Oracle.
A frame is the subset of a partition that a window function reads for each row. You set it with a clause after the window ORDER BY.
Frame units
ROWScounts physical rows before or after the current row.RANGEuses the values of theORDER BYcolumn. Rows with equal values (peers) enter the frame together.GROUPScounts peer groups instead of rows. PostgreSQL 11+ and SQLite 3.28+ support it. SQL Server does not.
SELECT region, sale_date, amount,
SUM(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM sales;The default frame
With an ORDER BY and no frame clause, the frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. This frame includes all peers of the current row, so tied rows can produce surprising results.
FIRST_VALUE, LAST_VALUE and NTH_VALUE
LAST_VALUE under the default frame returns the current row's value, not the partition's last value. Set an explicit full frame:
SELECT region, sale_date, amount,
LAST_VALUE(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_amount_in_region
FROM sales;NTH_VALUE(amount, 2) returns the second value in the frame, and it is also affected by the frame.
Named windows with the WINDOW clause
The WINDOW clause defines a window once and reuses it. SQL Server does not support it.
SELECT region, sale_date, amount,
SUM(amount) OVER w AS running_total,
AVG(amount) OVER w AS running_avg
FROM sales
WINDOW w AS (PARTITION BY region ORDER BY sale_date, id ROWS UNBOUNDED PRECEDING);Buckets and percentiles
| Function | Returns |
|---|---|
| NTILE(n) | Bucket number from 1 to n |
| PERCENT_RANK() | (rank - 1) / (rows - 1), from 0 to 1 |
| CUME_DIST() | Share of rows with a value less than or equal to the current row |
Practical patterns
For top-N per group, rank rows in a CTE and filter the outer query, because window functions cannot appear in WHERE:
WITH ranked AS (
SELECT region, salesperson, amount,
ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rn
FROM sales
)
SELECT region, salesperson, amount
FROM ranked
WHERE rn <= 3;Use LAG for period-over-period change. For gaps and islands, subtract ROW_NUMBER() from consecutive integers to group each streak.
Exercise
A query uses LASTVALUE(amount) with ORDER BY saledate and no frame clause. Why does it return the current row's amount?
Show answer
The default frame ends at CURRENT ROW, so the last value in the frame is the current row (or its peers). Add ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING to read the last value in the partition.