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 88/ 160
05. Window Functions & Analytical SQL

Window Frame Clauses (ROWS vs RANGE vs GROUPS)

Control which peer rows participate using ROWS, RANGE, or GROUPS frames.

AdvancedROWS · RANGE3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

The frame is the slice of rows a window function looks at for each row. ROWS counts rows, RANGE measures values, GROUPS counts sets of ties.

Think of it like…

Taking an average of "recent" exam scores: ROWS means "the last 3 exams I took", RANGE means "every exam in the last 30 days", and GROUPS means "the last 3 exam dates, counting every exam taken on each date".

Where you’ve seen it

Daily revenue has two rows for some days (two regions). SUM(rev) OVER (ORDER BY day ROWS 6 PRECEDING) covers 7 rows, which may be only 4 days; RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW covers exactly 7 calendar days, whatever the row count.

Words you’ll hear

Frame
The set of rows, relative to the current row, that the aggregate uses.
Peers
Rows with the same ORDER BY value as the current row.
Default frame
RANGE UNBOUNDED PRECEDING to CURRENT ROW with ORDER BY; the whole partition without it.
EXCLUDE
PostgreSQL 11+ option to drop the current row, its group or its ties from the frame.

Visual diagram

Loading interactive diagram

Theory & example queries

ROWS, RANGE and GROUPS

A frame is written as {ROWS | RANGE | GROUPS} BETWEEN start AND end, where start and end are UNBOUNDED PRECEDING, n PRECEDING, CURRENT ROW, n FOLLOWING or UNBOUNDED FOLLOWING. ROWS counts rows, so it's precise but blind to dates and ties.

RANGE measures distance in ORDER BY values: RANGE BETWEEN INTERVAL '7 days' PRECEDING AND CURRENT ROW needs a single date or number ORDER BY column (PostgreSQL 11+, MySQL 8; SQL Server allows only UNBOUNDED and CURRENT ROW with RANGE). In RANGE mode, CURRENT ROW means the current row and all its peers. GROUPS counts distinct ORDER BY values, so GROUPS 1 PRECEDING means the previous set of tied rows plus the current set.

A true 7-day window regardless of gapsQuery example
1Input dataStart from the source rows or state that the statement sees.
daily_revenue
4 rows
daily_revenue sample rows
dayamount
2026-11-15100
2026-11-17200
2026-11-2150
2026-11-2275
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  DAY,3  SUM(amount) OVER (4    ORDER BY5      DAY RANGE BETWEEN INTERVAL '6 days' PRECEDING6      AND CURRENT ROW7  ) AS rolling_7_day_revenue8FROM9  daily_revenue10ORDER BY11  DAY;
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/11
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
dayrolling_7_day_revenue
2026-11-15100
2026-11-17300
2026-11-21350
2026-11-22325

Note: Sample input uses amount values 100, 200, 50 and 75. RANGE measures six calendar days, so November 15 is included on November 21 but excluded on November 22; the source amount column is not part of the SELECT list.

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

Key takeaway: ROWS = row count, RANGE = value distance (and peers), GROUPS = tie groups.

The default frame and the LAST_VALUE trap

When OVER has ORDER BY but no frame, the frame is RANGE from the start of the partition to the current row, including peers. That's why a running SUM shows the same total on tied rows, and why LAST_VALUE(x) OVER (ORDER BY ts) returns the current row's value: the frame ends at the current row.

For the real last value in the partition, extend the frame: LAST_VALUE(x) OVER (PARTITION BY g ORDER BY ts ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING). Without ORDER BY, the frame is the whole partition, which is why SUM(x) OVER (PARTITION BY g) gives a group total.

Last price of the day on every rowQuery example
1Input dataStart from the source rows or state that the statement sees.
trades
4 rows
trades sample rows
trade_datesymbolpricets
2026-11-21AAPL198.209:15:00
2026-11-21AAPL198.815:30:00
2026-11-21MSFT410.109:15:00
2026-11-21MSFT410.4515:30:00
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  trade_date,3  symbol,4  price,5  LAST_VALUE(price) OVER (6    PARTITION BY7      trade_date,8      symbol9    ORDER BY10      ts ROWS BETWEEN UNBOUNDED PRECEDING11      AND UNBOUNDED FOLLOWING12  ) AS close_price13FROM14  trades15ORDER BY16  trade_date,17  ts;
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/17
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
trade_datesymbolpriceclose_price
2026-11-21AAPL198.2198.8
2026-11-21AAPL198.8198.8
2026-11-21MSFT410.1410.45
2026-11-21MSFT410.45410.45

Note: The query returns each trade beside the final price for that symbol and date.

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

Key takeaway: Write the frame explicitly whenever ORDER BY is present.

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 1Design

Decide what "nearby" means

Choose between a number of rows, a span of values (days, amounts) or a number of tie groups.

SQL at this step
1last 7 rows vs last 7 days
What to watch at this step
Dates with gaps
RANGE
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A window frame decides which rows around the current one an aggregate window function uses. ROWS counts physical rows ("the 2 rows before"). RANGE uses values of the ORDER BY column ("rows within 7 days before", and all rows tied with the current one). GROUPS counts groups of tied rows. With ORDER BY and no explicit frame, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.

Why it matters: The frame silently changes results: running totals that jump on tied rows, LAST_VALUE that returns the current row instead of the last, and rolling averages that cover the wrong dates. Advanced SQL interviews use frames to separate people who know window functions from people who have only copied them.

When to reach for it

  • Rolling metrics over calendar periods
  • Running totals where tie behaviour matters
  • LAST_VALUE and NTH_VALUE over the whole partition

When to avoid or be careful

  • Relying on the default frame with ORDER BY
  • ROWS-based "7-day" windows on data with gaps
  • LAST_VALUE without extending the frame

ROWS vs RANGE vs GROUPS

ROWS
Best for: Running totals per row, last-N-rows averages

Strengths: Precise and deterministic with a tiebreaker; supported everywhere.

Watch out: Ignores dates and ties: 7 rows may not be 7 days.

RANGE
Best for: Time-based windows, peer-inclusive totals

Strengths: Follows actual values, so gaps in dates are handled.

Watch out: Needs one ORDER BY column for offsets; limited in SQL Server.

GROUPS
Best for: "Previous N distinct values" with ties

Strengths: Treats each tie group as one step.

Watch out: Not in MySQL or SQL Server; rarely needed.

Interview signals & numbers to know

When this topic comes up

  • “Why does LAST_VALUE return the current row?”
  • “ROWS vs RANGE”
  • Running total repeats on tied rows
  • "Last 7 days" window
  • Window frame

Benchmarks & rules of thumb

RANGE … CURRENT ROW -
the default frame with ORDER BY
PostgreSQL 11 -
GROUPS, RANGE offsets and EXCLUDE
Whole partition -
the frame without ORDER BY

Common mistakes & follow-ups

Common interview mistakes

  • Using LAST_VALUE with the default frame and getting the current row's value.
  • Calling a ROWS 6 PRECEDING window "7 days" when some days are missing or repeated.
  • Assuming SQL Server supports RANGE with numeric or interval offsets.

Likely interviewer follow-ups

  • What's the default window frame when ORDER BY is present?
  • How do ROWS and RANGE differ when there are tied values?
  • How would you get the last value in each partition on every row?
Interview tip: Explain ROWS vs RANGE with one tied pair of rows, then show the LAST_VALUE fix. Those two examples cover what interviewers usually probe.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Window Frame Clauses (ROWS vs RANGE vs GROUPS) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Aggregate Window Functions (SUM() OVER, AVG() OVER, COUNT() OVER)
Next topic
Default Frame Trap with ORDER BY (RANGE UNBOUNDED PRECEDING AND CURRENT ROW)