window

NTH_VALUE

Reads the second frame row in this example, using one-based positions. Returns NULL when the frame has too few rows. PostgreSQL 17 respects NULLs. Example target: PostgreSQL 17; focused usage form.

Formal Syntax & Structure

sql syntaxsql
NTH_VALUE(x,2) OVER (PARTITION BY g ORDER BY x,id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)

Working Example

Example Snippetsql
WITH t(id,g,x) AS (VALUES (1,'A',10),(2,'A',20),(3,'A',20),(4,'A',40),(5,'B',7)) SELECT id, NTH_VALUE(x,2) OVER (PARTITION BY g ORDER BY x,id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS result FROM t ORDER BY id;
SQL Reference