Skip to main content

Overview

The NTH_VALUE() is a window function that allows you to access the value from the nth row within a specified window frame.

Syntax

The syntax for this function is as follows:

Parameters

  • value: column or expression for which you want to retrieve the value
  • n: positive integer (greater than zero) that determines the row number within the window frame from which to retrieve the value
  • PARTITION BY: optional clause, which divides the result set into partitions to which the NTH_VALUE() function is applied (if omitted, the entire result set is treated as a single partition)
  • ORDER BY: order of rows in each partition to which the function is applied
  • RANGE BETWEEN: range-based window frame relative to the current row

Example

For the needs of this section we will use a simplified version of the film table from the Pagila database, containing only the title, length and rating columns. The complete schema for the film table can be found on the Pagila database website.
The query below uses the NTH_VALUE() function to retrieve the title of the film with the second shortest duration, partitioning results by rating and ordering by length:
The above query will show the following table: