// window reference

SQL NTH_VALUE function

Returns the expression evaluated on the Nth row of the window frame, counting from 1; NULL when the frame has fewer than N rows so far.

Catégorie
Fenêtre
Returns
type of the expression
In this category
16 of 79

Syntaxe

NTH_VALUE(expr, n) OVER (ORDER BY x ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Not built in no NTH_VALUE; emulate with ROW_NUMBER in a subquery or LAG with a case expression
PostgreSQL Oui Supported under this name.
MySQL Oui MySQL 8.0+
SQLite Oui SQLite 3.25+
Oracle Oui Supported under this name.

Exemples

PostgreSQL

SELECT day, price,
       NTH_VALUE(price, 2) OVER (
         ORDER BY day
         ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS second_price
FROM prices;

Any engine

-- SQL Server emulation: the 2nd value per partition
WITH n AS (
  SELECT p0.*, ROW_NUMBER() OVER (PARTITION BY grp ORDER BY day) AS rn
  FROM prices p0
)
SELECT p.grp, p.day, p.price, n.price AS second_price
FROM prices p
LEFT JOIN n ON n.grp = p.grp AND n.rn = 2;

Bon à savoir

  • Same default-frame trap as LAST_VALUE: with only ORDER BY, the frame ends at the current row, so NTH_VALUE(..., 3) stays NULL until row 3 and never looks past it. Stretch the frame explicitly.
  • N counts from 1 and must be a positive integer; N = 0 or a negative N is an error, not NULL.
  • Only Oracle implements FROM LAST (count from the frame end) and IGNORE NULLS. MySQL parses both and refuses them ('doesn't yet support'); PostgreSQL and SQLite reject them as syntax errors.

Questions about NTH_VALUE

Why does NTH_VALUE return NULL for early rows?

Two reasons stack: the frame has fewer than N rows in the first place, and the default frame ends at the current row so later rows are invisible. With ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING every row sees the whole partition, so NULL then only appears when the partition has fewer than N rows (or the Nth value is itself NULL).

How do I get the Nth value in SQL Server?

No NTH_VALUE exists. Number rows with ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) in a CTE, keep the row where rn = N, and join it back.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.