Sub topic 12
FIRST_VALUE, LAST_VALUE and NTH_VALUE
This chapter assumes you can write OVER (PARTITION BY ... ORDER BY ...). It also assumes you know that a window has a frame, which is the slice of the partition that a function sees for each row. The three functions here are the "value" functions. They copy a column from one specific row of the frame onto every row of the output. Most of the trouble with them comes from the default frame.
What the three functions return
| Function | Returns |
|---|---|
| `FIRST_VALUE(expr)` | `expr` from the first row of the frame |
| `LAST_VALUE(expr)` | `expr` from the last row of the frame |
| `NTH_VALUE(expr, n)` | `expr` from the n-th row of the frame, counting from 1 |
All three read from the frame, not from the whole partition. This differs from LAG and LEAD, which count rows relative to the current row and ignore the frame. It also differs from ROW_NUMBER, which ignores the frame as well. If the frame is wrong, these functions return the wrong row, and the database raises no error.
Sample data
The examples use one small table. Run this setup first. It works in PostgreSQL, MySQL 8+ and SQLite 3.25+.
CREATE TABLE sales (
id INTEGER PRIMARY KEY,
region VARCHAR(20),
salesperson VARCHAR(20),
sale_date DATE,
amount INTEGER
);
INSERT INTO sales (id, region, salesperson, sale_date, amount) VALUES
(1, 'East', 'Ana', '2025-01-05', 100),
(2, 'East', 'Ben', '2025-01-12', 250),
(3, 'East', 'Ana', '2025-01-20', 175),
(4, 'East', 'Cara', '2025-02-02', 300),
(5, 'West', 'Dev', '2025-01-08', 400),
(6, 'West', 'Eli', '2025-01-15', 150),
(7, 'West', 'Dev', '2025-02-01', 220);FIRST_VALUE: comparing every row with a baseline
FIRST_VALUE is the safe one. The default frame starts at the first row of the partition, so the function works without any frame clause. A common use is measuring each row against the first row of its group.
SELECT
region,
sale_date,
amount,
FIRST_VALUE(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
) AS first_amount,
amount - FIRST_VALUE(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
) AS diff_from_first
FROM sales;For East, first_amount is 100 on every row, and diff_from_first is 0, 150, 75 and 200. The ORDER BY defines which row counts as "first". Without it, the order is unspecified and the result can change between runs.
You can also return a different column from the first row, such as the name of the earliest salesperson in the region: FIRST_VALUE(salesperson) OVER (PARTITION BY region ORDER BY sale_date, id). A GROUP BY query cannot do this without a join or a subquery.
LAST_VALUE and the default frame
When a window has an ORDER BY and no frame clause, the standard default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. The frame ends at the current row. So the "last" row of the frame is the current row, and LAST_VALUE returns the current row's own value.
SELECT
id,
amount,
LAST_VALUE(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
) AS last_default,
LAST_VALUE(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_full
FROM sales
WHERE region = 'East';The output for East shows the problem:
| id | amount | last_default | last_full |
|---|---|---|---|
| 1 | 100 | 100 | 300 |
| 2 | 250 | 250 | 300 |
| 3 | 175 | 175 | 300 |
| 4 | 300 | 300 | 300 |
The last_default column just repeats amount. On the final row it happens to match last_full, which makes the bug easy to miss in a short test.
Why ties make it worse
The default frame uses RANGE, so it includes all peers of the current row. Peers are rows with the same ORDER BY value. If two sales share a sale_date and you order only by sale_date, both rows are in each other's frame. LAST_VALUE then returns whichever peer the database happens to place last, and that choice is not guaranteed. Adding a unique tie-breaker such as id to the ORDER BY removes the ambiguity. The examples in this chapter do that.
Alternative: flip the order
You can avoid the frame problem for the last row by reversing the sort and using FIRST_VALUE:
SELECT
id,
region,
amount,
FIRST_VALUE(amount) OVER (
PARTITION BY region
ORDER BY sale_date DESC, id DESC
) AS latest_amount
FROM sales;The default frame of this window starts at the latest row, so FIRST_VALUE is reliable. Both approaches return the same values. The explicit frame states the intent more directly, and the reversed order can be easier to reuse when you also need FIRST_VALUE in the forward direction.
NTH_VALUE
NTH_VALUE(expr, n) returns the value from the n-th row of the frame. The argument n must be a positive integer. If the frame has fewer than n rows, the result is NULL.
SELECT
id,
region,
amount,
NTH_VALUE(amount, 2) OVER (
PARTITION BY region
ORDER BY sale_date, id
) AS second_default,
NTH_VALUE(amount, 2) OVER (
PARTITION BY region
ORDER BY sale_date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS second_full
FROM sales
WHERE region = 'East';| id | amount | second_default | second_full |
|---|---|---|---|
| 1 | 100 | NULL | 250 |
| 2 | 250 | 250 | 250 |
| 3 | 175 | 250 | 250 |
| 4 | 300 | 250 | 250 |
On row 1 the default frame holds only one row, so there is no second row and the result is NULL. The same default-frame logic that breaks LAST_VALUE makes NTH_VALUE return NULL for the early rows of each partition. Use the full frame when you want "the second sale in the region" on every row.
Frames, NULLs and dialect differences
- NULL inputs. By default these functions treat NULL as a value. If the first row's
amountis NULL,FIRST_VALUE(amount)returns NULL. The standard offersIGNORE NULLSto skip them. Oracle supports it. SQL Server supports it from SQL Server 2022. PostgreSQL, MySQL and SQLite do not accept it in these functions. There, you can filter NULLs in a subquery first, or use a different technique. - NTH_VALUE availability. PostgreSQL, MySQL 8, SQLite and Oracle provide it. SQL Server does not. Oracle also supports
FROM LAST, which counts from the end of the frame. Most other databases do not. - Frame type.
ROWScounts physical rows.RANGEincludes all peers. ForLAST_VALUEwith a full frame, both give the same answer. For a bounded frame such asROWS BETWEEN 2 PRECEDING AND CURRENT ROW, the choice changes which rows are included. - Check your version. Support for these options changes between releases. Test on your own database.
A frame can be bounded on purpose
A full frame is the most common choice, but it is not the only one. To return the amount from three sales ago, or to look at the highest-priority row among the last five, give the frame explicit bounds:
SELECT
id,
region,
amount,
FIRST_VALUE(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS amount_two_rows_back
FROM sales;For the first two rows in a partition, the frame is shorter, so FIRST_VALUE returns the first row available. For East, row 1 returns 100, row 2 returns 100, row 3 returns 100 and row 4 returns 250. This is not the same as LAG(amount, 2), which would return NULL for the first two rows.
Common mistakes
- Using
LAST_VALUEorNTH_VALUEwithout a frame clause and getting the current row orNULL. - Ordering on a non-unique column and getting different "first" or "last" rows between runs.
- Putting a value function in
WHERE. Window functions are not allowed there. Compute them in a CTE or subquery and filter outside. - Expecting
IGNORE NULLSto work on every database.
Exercise
Using the sales table, write a query that returns, for each West sale, the id, amount, and the amount of the most recent West sale (by saledate, then id) on every row. Use LASTVALUE. Then say what you would get for the amount column if you left out the frame clause.
Show answer
SELECT id, amount, LASTVALUE(amount) OVER (PARTITION BY region ORDER BY saledate, id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS latestamount FROM sales WHERE region = 'West'; The latestamount is 220 on all three rows (ids 5, 6, 7). Without the frame clause, the default frame ends at the current row, so latest_amount would repeat each row's own amount: 400, 150, 220.
Exercise
For East, NTH_VALUE(amount, 3) with the default frame returns NULL for which rows, and why? What single change gives 175 on every row?
Show answer
It returns NULL for ids 1 and 2. The default frame ends at the current row, so those rows have only one and two rows in their frames, and there is no third row. Ids 3 and 4 return 175 because their frames hold at least three rows. Adding ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING makes the frame cover all four East rows, so every row returns 175.