Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 89/ 160
05. Window Functions & Analytical SQL

Default Frame Trap with ORDER BY (RANGE UNBOUNDED PRECEDING AND CURRENT ROW)

Understand the default cumulative frame when ORDER BY is present.

AdvancedDefault Frame · RANGE · Cumulative3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

With ORDER BY and no frame, rows that tie are added together, so they all get the same running total.

Think of it like…

A race where runners who cross the line at the same instant share one finishing time: if you ask "how many have finished by now?" at either of them, the answer counts both.

Where you’ve seen it

A support dashboard plots cumulative tickets: COUNT(*) OVER (ORDER BY created_at). A bulk import created 40 tickets with the same timestamp, so the line jumps from 1,210 straight to 1,250 with 40 identical points instead of climbing one at a time. Switching to ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW with ORDER BY created_at, id makes each ticket add exactly one.

Words you’ll hear

Default frame
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, used when ORDER BY has no frame.
Peers
Rows with equal ORDER BY values; RANGE frames include all of them together.
ROWS frame
Counts physical rows, so each row's frame ends exactly at that row.
No ORDER BY
Without ORDER BY the frame is the whole partition.

Visual diagram

Loading interactive diagram

Theory & example queries

Where the default bites

The SQL standard default, followed by PostgreSQL, MySQL, SQL Server, Oracle and most other engines, ends the frame at the current row's last peer. With unique ORDER BY values, RANGE and ROWS give identical results, which is why the trap goes unnoticed in tests with tidy data. Ties appear in real data all the time: several orders on the same date, events in the same second, imports with one timestamp.

Three symptoms: running SUM or COUNT repeats the same value on tied rows and jumps by their combined amount; running AVG averages the tied rows together; and LAST_VALUE(x) OVER (ORDER BY t) returns the current row's value (or its last peer's), not the partition's final value, because the frame stops at the current row. FIRST_VALUE isn't affected, because the frame always starts at the beginning.

Seeing the differenceQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  DAY,3  amount,4  SUM(amount) OVER (5    ORDER BY6      DAY7  ) AS default_frame,8  SUM(amount) OVER (9    ORDER BY10      DAY,11      id ROWS BETWEEN UNBOUNDED PRECEDING12      AND CURRENT ROW13  ) AS rows_frame14FROM15  sales;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/15
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
dayamountdefault_framerows_frame
2026-11-01100300100
2026-11-01200300300
2026-11-02150450450
2026-11-0375525525

Note: Illustrative tied-day rows; RANGE by the default frame includes both rows of 2026-11-01, while ROWS stops at the current row.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

On tied days the two columns differ.

Key takeaway: Ties + default frame = shared running totals and wrong LAST_VALUE.

When RANGE is right, and the habit to adopt

Sometimes peers sharing a value is exactly what you want: a cumulative total by date where every order on a day should show the end-of-day figure. Even then, it's clearer to aggregate to one row per day first and run the cumulative sum over days, so nobody wonders whether the behaviour is intentional.

Adopt one habit: whenever a window function has ORDER BY and is an aggregate or a value function, write the frame explicitly and make ORDER BY unique with a tie-breaker such as id. It documents intent and makes results deterministic. In SQL Server it can also be faster, since the default RANGE frame uses an on-disk worktable while ROWS can use an in-memory spool.

LAST_VALUE done rightQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  customer_id,3  order_id,4  LAST_VALUE(order_id) OVER (5    PARTITION BY6      customer_id7    ORDER BY8      created_at,9      order_id ROWS BETWEEN UNBOUNDED PRECEDING10      AND UNBOUNDED FOLLOWING11  ) AS latest_order_id12FROM13  orders;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
customer_idorder_idlatest_order_id
42501530
42518530
42530530
77512524

Note: Illustrative orders; the full-partition frame gives every row the latest ID within its customer partition.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Write the frame and a tie-breaker every time; aggregate first if you want per-day totals.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Review

Spot ORDER BY without a frame

Look for SUM, COUNT, AVG or LAST_VALUE with OVER (… ORDER BY …) and no ROWS or RANGE clause.

SQL at this step
1SUM(amount) OVER (2  ORDER BY3    DAY4)
What to watch at this step
Default
RANGE … CURRENT ROW
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

When a window has ORDER BY but no frame clause, SQL uses the default frame RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE treats rows with the same ORDER BY value as peers and includes all of them, so tied rows get the same running total, and LAST_VALUE returns the last peer instead of the partition's last row. Writing ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW explicitly gives the row-by-row behaviour most people expect.

Why it matters: The trap is silent: the query runs, the numbers look plausible, and the bug only shows on rows with tied timestamps or dates. It surfaces as running totals that jump by two orders at once, statements where consecutive lines show the same balance, and LAST_VALUE columns that equal the current row. It's a favourite interview question because it separates people who know the defaults from people who guess.

When to reach for it

  • Explicit ROWS frames for every running total
  • UNBOUNDED FOLLOWING for LAST_VALUE over a partition
  • Code review checks on window functions

When to avoid or be careful

  • Relying on the default frame in shared or production SQL
  • ORDER BY on non-unique columns without a tie-breaker
  • LAST_VALUE with ORDER BY and no frame

Default RANGE vs explicit ROWS vs aggregate first

Default (RANGE … CURRENT ROW)
Best for: Deliberately giving tied rows the same cumulative value

Strengths: No extra syntax.

Watch out: Silent surprises on ties; wrong LAST_VALUE; slower in SQL Server.

Explicit ROWS frame + tie-breaker
Best for: Running totals, statements, cumulative counts

Strengths: One row at a time; deterministic; clear intent.

Watch out: Longer to write.

Aggregate to one row per value first
Best for: Cumulative totals by day or month

Strengths: No peers left, so RANGE and ROWS agree.

Watch out: Loses the individual rows.

Interview signals & numbers to know

When this topic comes up

  • “Why do two rows have the same running total?”
  • “LAST_VALUE returns the current row”
  • “What's the default window frame?”
  • Running totals with duplicate dates
  • Deterministic window results

Benchmarks & rules of thumb

RANGE … CURRENT ROW -
default frame with ORDER BY
Whole partition -
default frame without ORDER BY
0 -
difference between RANGE and ROWS when ORDER BY is unique

Common mistakes & follow-ups

Common interview mistakes

  • Testing a running balance on data with unique timestamps, then shipping it to data where many rows share a date.
  • Using LAST_VALUE(price) OVER (PARTITION BY product ORDER BY changed_at) to get the latest price and getting each row's own price.
  • Fixing the frame but leaving ORDER BY non-unique, so the order of tied rows still changes between runs.

Likely interviewer follow-ups

  • What frame does SUM() OVER (ORDER BY day) use, and when does it matter?
  • Why does LAST_VALUE often return the current row's value?
  • When would you deliberately want RANGE behaviour?
Interview tip: Name the default frame exactly, then show a two-row tie with both results. A tiny worked example proves you understand peers, not just the rule.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Default Frame Trap with ORDER BY (RANGE UNBOUNDED PRECEDING AND CURRENT ROW) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Window Frame Clauses (ROWS vs RANGE vs GROUPS)
Next topic
Calculating Running Totals & Cumulative Distributions