Window Frames: ROWS / RANGE + NTILE in SQL
Moving averages, quartiles, and the LAST_VALUE trap
Frames bound participating peers: ROWS counts physical rows (precise, stepwise); RANGE groups ORDER BY peers (ties move together); GROUPS groups peer sets. Default RANGE-to-current-peer surprises with duplicate keys β explicit ROWS is predictable. FIRST_VALUE/LAST_VALUE/NTH_VALUE pick positions; bare LAST_VALUE returns the current row (frame ends there) unless given UNBOUNDED FOLLOWING. NTILE(n) buckets into n near-equal groups.
ROWS is physical
Counts rows β precise, stepwise. The predictable choice.
RANGE groups peers
Ties on ORDER BY move together β totals jump on duplicate keys.
LAST_VALUE trap
Default frame ends at current row β bare LAST_VALUE returns current row, not partition end. Needs UNBOUNDED FOLLOWING.
NTILE buckets
Splits ordered rows into n near-equal groups; remainders to early buckets. Empty OVER () is whole-result window.
1SELECT name, NTILE(2) OVER (ORDER BY salary DESC) AS half FROM employees ORDER BY salary DESC;
| name | half |
|---|---|
| Cynthia | 1 |
| Alice | 1 |
| Farid | 1 |
| Elena | 2 |
| Bob | 2 |
| David | 2 |
Six rows split into two near-equal halves: top three earners in bucket 1, bottom three in bucket 2. Same OVER shape with ROWS BETWEEN builds moving averages; with LAST_VALUE it must carry the full-partition frame.
3-row moving average
Explicit frame slides predictably.
1SELECT name, AVG(salary) OVER (ORDER BY id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg FROM employees ORDER BY id;
| name | moving_avg |
|---|---|
| Alice | 85000 |
| Bob | 68500 |
| Cynthia | 76000 |
| David | 63333.33 |
| Elena | 65333.33 |
| Farid | 59333.33 |
Halves + last-in-dept
NTILE buckets; LAST_VALUE needs full frame.
1SELECT name, NTILE(2) OVER (ORDER BY salary DESC) AS half, LAST_VALUE(salary) OVER (PARTITION BY department ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_in_dept FROM employees ORDER BY salary DESC LIMIT 2;
| name | half | last_in_dept |
|---|---|---|
| Cynthia | 1 | 73000 |
| Alice | 1 | 73000 |
Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.