NTH_VALUE is a ANSI SQL window function that returns the value of the nth row in the defined window frame, relative to the current row. Unlike FIRST_VALUE or LAST_VALUE that always fetch the first or last row of the frame, NTH_VALUE lets you pick any position by supplying an integer n. The function is computed after the ORDER BY clause within the OVER clause has been applied, and respects the frame mode (RANGE or ROWS) and boundaries. If the requested nth row lies outside the current frame, the result is NULL. Because the function is evaluated once per row, performance considerations are similar to other window functions – indexes on the ORDER BY columns help. n must be a positive integer constant or expression; zero or negative values raise an error.
value_expression
- Any valid column or expression whose nth value you need.n
- Positive INTEGER specifying the row position to return (1 is the first row).partition_expression_list
- Optional. Divides the result set into partitions.sort_expression_list
- Defines row order inside each partition.frame_start, frame_end
- Optional frame boundaries (e.g., UNBOUNDED PRECEDING, CURRENT ROW, n PRECEDING/FOLLOWING).FIRST_VALUE, LAST_VALUE, LAG, LEAD, PERCENTILE_CONT, WINDOW FRAME
SQL:2008 standard (optional feature T611)
LAG returns a value offset from the current row by a specified number of rows, regardless of frame boundaries. NTH_VALUE returns the value of the nth row of the window frame, which can be anywhere relative to the current row.
Most databases require n to be an integer literal or bind parameter. Using a column reference is not allowed and results in a syntax error.
Ensure your frame includes all rows by adding `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING`. Otherwise, when the current row is earlier than the nth position, NTH_VALUE returns NULL.
No. DISTINCT cannot be applied inside a window function. Filter or aggregate your data in a subquery first, then apply NTH_VALUE.