Returns the value evaluated of the nth row of the specified window frame (starting at the first row). If the specified row does not exist, NTH_VALUE returns NULL.

See also FIRST_VALUE, which returns the first value evaluated in the specified window frame. For more information on usage, please refer to Window Functions.

Syntax

NTH_VALUE( <expression>, <n> ) OVER ( [ PARTITION BY <partition_by> ] ORDER BY <order_by> [ASC|DESC] )

Parameters

ParameterDescriptionSupported input types
<expression>A SQL expression of any type to evaluate.Any
<n>A constant integer in range [1, max of datatype INTEGER] to indicate the row number to evaluate.INTEGER
<partition_by>An expression used for the PARTITION clause.Any
<order_by>An expression used for the order by clause.Any

Return Types

Same as input type.

This function respects NULL values, and results will be ordered with default null ordering NULLS LAST unless otherwise specified in the ORDER BY clause. If applied without an ORDER BY clause, the order will be undefined.

Example

The example below returns the student with the second highest test score for each grade level. Notice that the function returns NULL for the first row in each partition, unless the value of the expression for first and second rows of the partition are equal.

SELECT
    nickname,
    level,
    current_score,
    NTH_VALUE(first_name, 2) OVER (PARTITION BY level ORDER BY current_score DESC) second_highest_score
FROM
    players;

Returns:

nicknamelevelcurrent_scoresecond_highest_score
ymatthews985Sammy
rileyjon1089null
kennethpark1194null
sabrina2112100burchdenise