Xorthax can now get the first and last values in a group. But what if he wants something in the middle?
“What is the 2nd value?” “What is the 3rd value?”
That’s what NTH_VALUE() does.
NTH_VALUE() returns the value from a specific position in a sequence.
NTH_VALUE(column, n) OVER (
PARTITION BY column
ORDER BY column
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
)
This works because:
PARTITION BY defines the groupORDER BY defines the sequence| CustomerID | OrderDate | Amount |
|---|---|---|
| A | 2024-01-01 | 100 |
| A | 2024-01-03 | 120 |
| A | 2024-01-05 | 150 |
| B | 2024-01-02 | 200 |
| B | 2024-01-06 | 50 |
SELECT CustomerID, OrderDate, Amount,
NTH_VALUE(Amount, 2) OVER (
PARTITION BY CustomerID
ORDER BY OrderDate
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS SecondAmount
FROM Orders;
Result:
| CustomerID | OrderDate | Amount | SecondAmount |
|---|---|---|---|
| A | 2024-01-01 | 100 | 120 |
| A | 2024-01-03 | 120 | 120 |
| A | 2024-01-05 | 150 | 120 |
| B | 2024-01-02 | 200 | 50 |
| B | 2024-01-06 | 50 | 50 |
Each row now shows the value from the second position in its group.
PARTITION BY CustomerID creates a group for each customer.
ORDER BY OrderDate defines the sequence within each group.
NTH_VALUE(Amount, 2) looks at the second row in that sequence.
That value is then repeated for every row in the group.
If a group has fewer than n rows, the result will be null.
⚠️ Important: If you leave out the window frame, SQL only looks at rows up to the current row.
That means NTH_VALUE() may return different results for different rows—or null—instead of the true nth value in the group.
For each order, show the totalamount from the second order based on orderdate.
| Column | Type |
|---|---|
| orderid | bigint |
| customerid | bigint |
| orderdate | timestamp without time zone |
| totalamount | double precision |
| status | text |
| Column |
|---|
| orderid |
| orderdate |
| totalamount |
| second_amount |
Now that you can pull values from specific positions, you’re ready to assign positions to rows.
Next, you’ll learn how to number rows.