Value Functions: FIRST_VALUE(), LAST_VALUE(), NTH_VALUE()
Pull first, last, or nth values from a window frame carefully.
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
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.
| trade_date | symbol | price | ts |
|---|---|---|---|
| 2026-11-21 | AAPL | 198.2 | 09:15:00 |
| 2026-11-21 | AAPL | 198.8 | 15:30:00 |
| 2026-11-21 | MSFT | 410.1 | 09:15:00 |
SELECT trade_day, ts, price, FIRST_VALUE(price) OVER w AS open_price, LAST_VALUE(price) OVER w AS close_priceFROM tradesWINDOW w AS ( PARTITION BY trade_day ORDER BY ts ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING );PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output3 sample rows
| trade_day | ts | price | open_price | close_price |
|---|---|---|---|---|
| 2026-11-18 | 09:15:00 | 101.2 | 101.2 | 104.8 |
| 2026-11-18 | 10:00:00 | 102.5 | 101.2 | 104.8 |
| 2026-11-18 | 15:30:00 | 104.8 | 101.2 | 104.8 |
Note: Illustrative trades; the full ROWS frame makes the first and last prices constant for the partition.
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.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT customer_id, id, amount, NTH_VALUE(amount, 2) OVER ( PARTITION BY customer_id ORDER BY created_at, id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) AS second_amountFROM orders;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output4 sample rows
| customer_id | id | amount | second_amount |
|---|---|---|---|
| 42 | 501 | 300 | 450 |
| 42 | 507 | 450 | 450 |
| 42 | 518 | 900 | 450 |
| 77 | 512 | 120 | NULL |
Note: Illustrative partitions; NTH_VALUE is NULL for customer 77 because its partition contains fewer than two rows.
Key takeaway: Use full frames for NTH_VALUE, add tiebreakers, and watch NULLs.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Define the group and order
Partition by the entity (user, day) and order by time, with a unique tiebreaker.
PARTITION BY user_idORDER BY event_at, idWhen 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
Strengths: One pass, keeps all rows.
Watch out: Frame-sensitive; ties and NULLs need care.
Strengths: Gets the whole row.
Watch out: More code and a join.
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?
Knowledge check
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.