Skip to content

NTH_VALUE

NTH_VALUE(expression, nth) OVER ([PARTITION BY partition_expression] ORDER BY sort_expression [ASC | DESC] [NULLS { FIRST | LAST }])

Section titled “NTH_VALUE(expression, nth) OVER ([PARTITION BY partition_expression] ORDER BY sort_expression [ASC | DESC] [NULLS { FIRST | LAST }])”
  • expression: The column or expression that will be evaluated. This parameter represents the value you want to retrieve at the nth position within the defined partition or entire result set.
  • nth: The position within the result set to be taken. This is a positive integer that represents the row position within the ordered partition or result set.
  • partition by partition_expression: This divides the query result into different groups, or partitions, based on one or multiple columns. It’s optional and if it’s not included, the function will treat the entire result set as a single partition.
  • order by sort_expression: This determines the order of the data in each partition or the entire result set. The function will calculate the nth value based on this order.
  • asc | desc: These options determine whether the sort order is ascending (ASC) or descending (DESC). The default is ASC if it’s not specified.
  • nulls { first | last }: This determines the position of NULLs in the ordered partition or result set. If NULLS FIRST is specified, NULLs are sorted to the beginning; If NULLS LAST is specified, NULLs sort to the end.
CREATE TABLE tests (
id serial PRIMARY KEY,
name varchar(100),
score integer
);
INSERT INTO tests (name, score)
VALUES ('John', 90), ('Sandy', 85), ('Mia', 95), ('Ryan', 92), ('Sophia', 88);
SELECT name, score,
NTH_VALUE(name, 2) OVER(
ORDER BY score DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
AS second_highest_score_name
FROM tests;
namescoresecond_highest_score_name
Mia95Ryan
Ryan92Ryan
John90Ryan
Sophia88Ryan
Sandy85Ryan

In the example given, the NTH_VALUE function is used to find the name of the person with the second highest test score. By using the NTH_VALUE function with the parameters name, 2, the function will return the name for the second largest score in the list when ordered in descending order. The data is analyzed within the entire table (ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING). Therefore, ‘Ryan’ appears as the second highest scorer in each row in the second_highest_score_name column.