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

Value Functions: FIRST_VALUE(), LAST_VALUE(), NTH_VALUE()

Pull first, last, or nth values from a window frame carefully.

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

In plain words

These functions grab a value from the first, last or nth row of the group and show it on every row.

Think of it like…

Marking a race: every runner's split time is shown next to the leader's time (FIRST_VALUE), the last finisher's time (LAST_VALUE), and the time of whoever came third (NTH_VALUE).

Where you’ve seen it

Each user's first acquisition channel on every event: SELECT user_id, event_at, channel, FIRST_VALUE(channel) OVER (PARTITION BY user_id ORDER BY event_at) AS first_channel FROM events; lets you attribute later purchases to how the user originally arrived.

Words you’ll hear

FIRST_VALUE
Value from the first row of the frame.
LAST_VALUE
Value from the last row of the frame (the current row, with the default frame).
NTH_VALUE(x, n)
Value from the nth row of the frame; NULL if the frame has fewer rows.
Full-partition frame
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.

Visual diagram

Loading interactive diagram

Theory & example queries

FIRST_VALUE and the LAST_VALUE trap

FIRST_VALUE works as expected with the default frame, because every frame starts at the beginning of the partition. LAST_VALUE doesn't: with ORDER BY and no explicit frame, the frame ends at the current row (and its peers), so LAST_VALUE returns the current row's own value.

Fix it by extending the frame, ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, or avoid LAST_VALUE entirely by using FIRST_VALUE with the order reversed (ORDER BY ts DESC), which many people find clearer.

Opening and closing price per dayQuery example
1Input dataStart from the source rows or state that the statement sees.
trades
3 rows
trades sample rows
trade_datesymbolpricets
2026-11-21AAPL198.209:15:00
2026-11-21AAPL198.815:30:00
2026-11-21MSFT410.109:15:00
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  trade_day,3  ts,4  price,5  FIRST_VALUE(price) OVER w AS open_price,6  LAST_VALUE(price) OVER w AS close_price7FROM8  trades9WINDOW10  w AS (11    PARTITION BY12      trade_day13    ORDER BY14      ts ROWS BETWEEN UNBOUNDED PRECEDING15      AND UNBOUNDED FOLLOWING16  );
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/16
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
trade_daytspriceopen_priceclose_price
2026-11-1809:15:00101.2101.2104.8
2026-11-1810:00:00102.5101.2104.8
2026-11-1815:30:00104.8101.2104.8

Note: Illustrative trades; the full ROWS frame makes the first and last prices constant for the partition.

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

Key takeaway: Give LAST_VALUE a full-partition frame, or use FIRST_VALUE with DESC.

NTH_VALUE, ties and NULLs

NTH_VALUE(x, 2) returns the second row's value in the frame. With the default frame, rows before the second one get NULL, because their frame doesn't contain a second row yet; use the full-partition frame if every row should see it. It's handy for "second purchase amount" without a self-join. (SQL Server doesn't support NTH_VALUE.)

If the ORDER BY has ties, which row counts as first or last is arbitrary, so add a unique tiebreaker. NULL values count as rows: FIRST_VALUE may return NULL. Oracle, Snowflake, BigQuery and SQL Server 2022 support IGNORE NULLS to skip them; PostgreSQL and MySQL don't, so filter or use COALESCE-based workarounds there.

Each customer's second order amount on every rowQuery 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  id,4  amount,5  NTH_VALUE(amount, 2) OVER (6    PARTITION BY7      customer_id8    ORDER BY9      created_at,10      id ROWS BETWEEN UNBOUNDED PRECEDING11      AND UNBOUNDED FOLLOWING12  ) AS second_amount13FROM14  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/14
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
customer_ididamountsecond_amount
42501300450
42507450450
42518900450
77512120NULL

Note: Illustrative partitions; NTH_VALUE is NULL for customer 77 because its partition contains fewer than two rows.

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

Key takeaway: Use full frames for NTH_VALUE, add tiebreakers, and watch NULLs.

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

Define the group and order

Partition by the entity (user, day) and order by time, with a unique tiebreaker.

SQL at this step
1PARTITION BY2  user_id3ORDER BY4  event_at,5  id
What to watch at this step
Tiebreaker
for stable results
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

FIRST_VALUE(x), LAST_VALUE(x) and NTH_VALUE(x, n) return the value of x from the first, last or nth row of the window frame. Combined with PARTITION BY and ORDER BY they answer "each user's first channel", "the day's closing price" or "the second purchase amount", while keeping every row. LAST_VALUE and NTH_VALUE depend on the frame, which is where most bugs come from.

Why it matters: Comparing every row with a reference row (the first order, the opening price, the previous best) is common in analytics, and LAST_VALUE returning the current row's value instead of the last is one of the most famous window-function traps.

When to reach for it

  • First-touch attribution per user
  • Opening and closing values per period
  • Comparing each row with the first or best row

When to avoid or be careful

  • LAST_VALUE with the default frame
  • Ordering by a non-unique column without a tiebreaker
  • Using MAX when you actually need the latest value in time

Ways to get a reference row's value

FIRST_VALUE / LAST_VALUE / NTH_VALUE
Best for: Showing a reference value on every row

Strengths: One pass, keeps all rows.

Watch out: Frame-sensitive; ties and NULLs need care.

ROW_NUMBER = 1 in a CTE, then join
Best for: When you need several columns of the reference row

Strengths: Gets the whole row.

Watch out: More code and a join.

MIN / MAX OVER
Best for: The smallest or largest value, regardless of position

Strengths: No frame trap.

Watch out: Gives the extreme value, not the first or last in time.

Interview signals & numbers to know

When this topic comes up

  • “Each user's first channel”
  • “Why does LAST_VALUE return the current row?”
  • “Opening and closing price”
  • “Second purchase amount”
  • First-touch attribution

Benchmarks & rules of thumb

UNBOUNDED FOLLOWING -
needed for a true LAST_VALUE
NULL -
NTH_VALUE before the nth row is in the frame
SQL Server 2022 -
added IGNORE NULLS

Common mistakes & follow-ups

Common interview mistakes

  • Using LAST_VALUE(price) OVER (PARTITION BY day ORDER BY ts) and getting each row's own price.
  • Using MAX(created_at) to find the latest status instead of the status of the latest row.
  • Leaving ties in the order, so the "first" channel changes between runs.

Likely interviewer follow-ups

  • Why does LAST_VALUE often return the current row's value?
  • How would you show each user's first and most recent order amount on every order?
  • What does NTH_VALUE return for rows before the nth one?
Interview tip: Lead with the LAST_VALUE trap and its two fixes (full frame, or FIRST_VALUE DESC). It's the question interviewers almost always ask about these functions.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Value Functions: FIRST_VALUE(), LAST_VALUE(), NTH_VALUE() with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Offset Functions: LAG() & LEAD() (Accessing Previous & Next Rows)
Next topic
Aggregate Window Functions (SUM() OVER, AVG() OVER, COUNT() OVER)