SQL Window Frames: ROWS vs RANGE and the LAST_VALUE Trap
Understand SQL window frames with duplicate sort keys, numeric gaps and LAST_VALUE. Includes tested SQLite queries, expected results and an independent Python oracle.
A window ORDER BY does not necessarily give an aggregate a one-row-at-a-time running frame, and LAST_VALUE does not necessarily mean the last row of the partition. The result depends on the frame and its peer groups. Make the partition, ordering and frame separate decisions, then test duplicate ordering values. This guide demonstrates the differences with real SQLite execution and explains which conclusions still need verification on another database.
Separate the partition, ordering and frame
PARTITION BY decides which rows belong to the same calculation group. The ORDER BY inside OVER defines their window ordering. The frame selects the rows used by a frame-sensitive calculation at the current position. Confusing these roles can produce a query that looks sorted correctly while computing the wrong cumulative value.
A window calculation retains the result rows rather than collapsing each partition into one output row as an ordinary grouped aggregate would. Its ordering is also separate from final presentation. Use an outer ORDER BY when you need predictable output order; do not assume that an OVER clause guarantees how the result is displayed.
Before writing the frame, state the intended question: a cumulative total after each event, a cumulative total through all events at the same sort value, a fixed number of neighboring rows, or a range of ordering values. Those are different calculations. Adding syntax until a sample looks right is less reliable than identifying the intended row set first.
Source: PostgreSQL window tutorial: ordering, frames and query filtering ↗
Start with duplicate days and an actual gap
The synthetic fixture has two accounts. Account A contains two events at day 1, an event at day 2, and another at day 4. The day column is an integer ordering coordinate in this example; it is not a SQL date or timestamp. Account B provides a second partition so a missing PARTITION BY cannot pass unnoticed.
The unique id supplies an explicit order between events on the same day when a row-by-row calculation needs one. It is a teaching tie-breaker, not a claim that an arbitrary database identifier expresses business chronology. In a real pipeline, choose a stable sequence that matches the meaning of an event.
CREATE TABLE events(id INTEGER PRIMARY KEY, account TEXT, day INTEGER, amount INTEGER);
INSERT INTO events VALUES
(1,'A',1,10), (2,'A',1,20), (3,'A',2,5),
(4,'A',4,7), (5,'B',1,3), (6,'B',3,4);Source: SQLite window functions: frame types, peers and boundaries ↗
Why a default running sum can jump across peers
For these ordinary ordered windows, SQLite documents the default frame as RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW with its default exclusion behavior. The PostgreSQL documentation also explains that the default ordered frame includes peers through the current ordering group. Rows tied on all window ordering expressions are peers.
For SUM(amount) ordered only by day, the two day-1 events in account A are peers. Both therefore see the cumulative total 30. An explicit ROWS cumulative frame with ORDER BY day,id produces 10 and then 30. Neither output is inherently defective: one is a value-group cumulative total and the other is an event-sequence cumulative total.
Do not add id to every ordering specification automatically. It makes these events distinct ordering positions and changes the peer groups. That can be appropriate for a sequence but wrong for a report meant to give every event on the same day the same cumulative daily total. Treat the tie-breaker as a semantic choice.
| A event id | day | amount | Default SUM ordered by day | ROWS SUM ordered by day,id |
|---|---|---|---|---|
| 1 | 1 | 10 | 30 | 10 |
| 2 | 1 | 20 | 30 | 30 |
| 3 | 2 | 5 | 35 | 35 |
| 4 | 4 | 7 | 42 | 42 |
Source: SQLite window functions: frame types, peers and boundaries ↗
Compare the frames in one executable query
Run the following after creating the fixture in an SQLite database. It keeps the ordering expressions explicit for each calculation. The default sum intentionally uses day alone, while the event-sequence columns use day,id. The output ORDER BY is present for readable, reproducible display.
The numeric RANGE example requires a single numeric ordering expression in SQLite. Its one-unit preceding bound includes rows whose day falls between the current value minus one and the current value, including peers. The ROWS example instead includes the immediately preceding ordered row and the current row. A missing day therefore matters to RANGE in a way that it does not matter to ROWS.
SELECT id, account, day, amount,
SUM(amount) OVER (PARTITION BY account ORDER BY day) AS default_sum,
SUM(amount) OVER (PARTITION BY account ORDER BY day, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS row_sum,
LAST_VALUE(amount) OVER (PARTITION BY account ORDER BY day, id) AS default_last,
LAST_VALUE(amount) OVER (PARTITION BY account ORDER BY day, id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS partition_last,
SUM(amount) OVER (PARTITION BY account ORDER BY day
RANGE BETWEEN 1 PRECEDING AND CURRENT ROW) AS range_one,
SUM(amount) OVER (PARTITION BY account ORDER BY day, id
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS rows_one
FROM events ORDER BY account, day, idSource: SQLite window functions: frame types, peers and boundaries ↗
A row count is not a value distance
At day 4 in account A, RANGE BETWEEN 1 PRECEDING AND CURRENT ROW covers integer day values from 3 through 4. There is no day-3 event, so only amount 7 contributes. ROWS BETWEEN 1 PRECEDING AND CURRENT ROW takes the day-2 event and the day-4 event, totaling 12. The previous row need not be one day earlier.
The complete A results for these two columns are 30, 30, 35, 7 for numeric RANGE and 10, 30, 25, 12 for ROWS. This example is useful precisely because it combines duplicate values with a gap. A fixture containing one event at every consecutive value can conceal both distinctions.
A numeric offset on this integer column is not a portable recipe for a calendar interval over timestamps. Date arithmetic, interval syntax, supported ordering types and offset restrictions depend on the database. Choose a representation and query appropriate to the engine, then test daylight-saving, time-zone or missing-period behavior if those matter to the actual application.
Source: SQLite window functions: frame types, peers and boundaries ↗
LAST_VALUE uses the frame endpoint
LAST_VALUE evaluates the value at the end of its frame. It is not a shorthand for the maximum value and does not inherently request the last row of the entire partition. In this query, the unique day,id ordering makes the default frame end at the current row, so default_last repeats the current amount.
The partition_last column explicitly extends the frame to UNBOUNDED FOLLOWING. Every A row therefore sees amount 7 from the last ordered A event. It does not see 20 merely because 20 is the largest amount. A complete ordering remains important: if several rows tie at the final position, choose how the application defines which one is last.
Do not assume that every window function responds to a frame in the same way. Ranking and offset functions have their own definitions. Check the documentation for the specific function instead of trying to change an arbitrary ROWS clause until a rank or lag result changes.
Source: PostgreSQL window functions: frame-sensitive LAST_VALUE and function definitions ↗
Use the whole partition when no running boundary is intended
For an aggregate that should show the entire account total beside every event, SUM(amount) OVER (PARTITION BY account) expresses that intent without a window ordering. In this fixture every A event receives 42 and every B event receives 7. An outer ORDER BY can still arrange the display by account, day and id without turning the total into a running calculation.
This is different from adding GROUP BY account, which changes the result row granularity. Decide whether the report needs one row per account or one row per event carrying an account-level measure. The frame question comes after that decision; otherwise a syntactically valid rewrite can silently change the shape of the report.
Source: PostgreSQL window functions: frame-sensitive LAST_VALUE and function definitions ↗
Filtering can change the rows a window sees
Rows removed by the query WHERE clause do not participate in that query level's window calculation. For account A, filtering to day >= 2 before the running sum yields 5 and 12. If the intended result is the full-account cumulative total displayed only from day 2 onward, calculate first in a CTE or subquery and filter the computed result outside it.
The outer-filter version below yields 35 and 42. Keep the account restriction inside this particular example because both variants intentionally calculate account A only. In a multi-account version, preserve PARTITION BY account. Moving filters across query levels without checking their purpose can change more than the displayed rows.
Likewise, a join that duplicates an event can inflate the row set before the window runs. A surprising running total is not always caused by RANGE. Inspect the input cardinality and the actual intermediate rows as well as the frame. Do not use a blanket DISTINCT to conceal a multiplicity problem without understanding which event rows are legitimate.
WITH totals AS (
SELECT id, day,
SUM(amount) OVER (ORDER BY day,id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS total
FROM events WHERE account='A'
)
SELECT id,total FROM totals WHERE day>=2 ORDER BY day,id;Source: PostgreSQL window tutorial: ordering, frames and query filtering ↗
Reproduce the results with an independent oracle
Save the following as window_frame_lab.py and run python3 window_frame_lab.py. It uses Python's standard sqlite3 module and an in-memory database. It writes no database file and contacts no service. The ordinary-Python oracle computes each expected row set directly without calling SQL window functions.
On Python 3.12.14 with SQLite 3.53.1, the script passed 204 datasets and 1,378 row-oracle comparisons, plus five fixed-result assertions and the two filtering-stage assertions. It includes reversed insertion order, seeded generated inputs, multiple accounts, duplicate ordering values, gaps, negative integer amounts and an empty table.
The generated cases use bounded integers and non-null values. They are not performance benchmarks or exhaustive SQL conformance tests. The lab does not test NULL ordering, collations, descending offsets, EXCLUDE, GROUPS, numeric overflow, timestamps or a PostgreSQL server. The PostgreSQL discussion is documentation-based; run the relevant queries on your own engine before relying on cross-engine behavior.
import random
import sqlite3
QUERY = '''SELECT id, account, day, amount,
SUM(amount) OVER (PARTITION BY account ORDER BY day) AS default_sum,
SUM(amount) OVER (PARTITION BY account ORDER BY day, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS row_sum,
LAST_VALUE(amount) OVER (PARTITION BY account ORDER BY day, id) AS default_last,
LAST_VALUE(amount) OVER (PARTITION BY account ORDER BY day, id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS partition_last,
SUM(amount) OVER (PARTITION BY account ORDER BY day
RANGE BETWEEN 1 PRECEDING AND CURRENT ROW) AS range_one,
SUM(amount) OVER (PARTITION BY account ORDER BY day, id
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS rows_one
FROM events ORDER BY account, day, id'''
FIXTURE = [(1, 'A', 1, 10), (2, 'A', 1, 20), (3, 'A', 2, 5),
(4, 'A', 4, 7), (5, 'B', 1, 3), (6, 'B', 3, 4)]
# Independent ordinary-Python oracle: no SQL/window calls.
def expected(rows):
answer = []
for account in sorted({r[1] for r in rows}):
group = sorted((r for r in rows if r[1] == account), key=lambda r: (r[2], r[0]))
for i, row in enumerate(group):
day = row[2]
peer_prefix = sum(r[3] for r in group if r[2] <= day)
row_prefix = sum(r[3] for r in group[:i + 1])
range_one = sum(r[3] for r in group if day - 1 <= r[2] <= day)
rows_one = sum(r[3] for r in group[max(0, i - 1):i + 1])
answer.append((*row, peer_prefix, row_prefix, row[3], group[-1][3], range_one, rows_one))
return answer
cases = row_comparisons = 0
with sqlite3.connect(':memory:') as db:
db.execute('CREATE TABLE events(id INTEGER PRIMARY KEY, account TEXT, day INTEGER, amount INTEGER)')
def run(rows):
global cases, row_comparisons
db.execute('DELETE FROM events')
db.executemany('INSERT INTO events VALUES (?,?,?,?)', rows)
actual = db.execute(QUERY).fetchall()
assert actual == expected(rows), (rows, actual)
cases += 1
row_comparisons += len(actual)
return actual
actual = run(FIXTURE)
assert [r[4] for r in actual[:4]] == [30, 30, 35, 42]
assert [r[5] for r in actual[:4]] == [10, 30, 35, 42]
assert [r[7] for r in actual[:4]] == [7, 7, 7, 7]
assert [r[8] for r in actual[:4]] == [30, 30, 35, 7]
assert [r[9] for r in actual[:4]] == [10, 30, 25, 12]
assert run(list(reversed(FIXTURE))) == actual
# Filter before the window versus after computing the running total.
run(FIXTURE)
before = db.execute('''SELECT id, SUM(amount) OVER (ORDER BY day,id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM events WHERE account='A' AND day>=2 ORDER BY day,id''').fetchall()
after = db.execute('''WITH totals AS (
SELECT id, day, SUM(amount) OVER (ORDER BY day,id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS total
FROM events WHERE account='A')
SELECT id,total FROM totals WHERE day>=2 ORDER BY day,id''').fetchall()
assert before == [(3, 5), (4, 12)]
assert after == [(3, 35), (4, 42)]
rng = random.Random(7321)
for case in range(200):
rows = [(i, rng.choice(['A', 'B']), rng.randint(-3, 6), rng.randint(-5, 20))
for i in range(1, rng.randint(1, 12) + 1)]
rng.shuffle(rows)
run(rows)
run([])
print(f'SQLite {sqlite3.sqlite_version}: {cases} datasets, {row_comparisons} row-oracle comparisons passed.')
print('Filter-stage and five fixed-result assertions also passed; no PostgreSQL server tested.')Source: SQLite window functions: frame types, peers and boundaries ↗
Review the row set before tuning the query
When a window result surprises you, display the partition key, all ordering expressions, a unique event identifier and the measure beside the result. Add duplicate sort keys and a gap to a small fixture. Verify the input rows, the frame membership and the last-row definition before changing indexes or execution settings.
Once the query expresses the intended calculation, evaluate its execution plan and resource use on representative data in the actual database. A correct six-row fixture does not establish acceptable memory, sort cost or latency at production scale. Keep the regression fixture as a correctness check while making any later performance change.
Use an explicit frame when its boundaries are part of the application contract, and document why its ordering keys are present. This makes future edits safer: replacing a daily peer-group total with an event-sequence total can be a meaningful behavior change even when the SQL still returns the same columns.
Source: SQLite window functions: frame types, peers and boundaries ↗
Your next steps
- Choose partition, ordering and frame independently; duplicate ordering values expose peer behavior.
- Use a complete ordering for sequence-dependent results, and extend LAST_VALUE to the intended endpoint explicitly.
- Test filtering stage and input multiplicity, then verify syntax, semantics and performance on the target database.
Sources & official resources
Linked resources checked on 2026-10-29. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →