22016
PostgreSQLERRORNotableData ExceptionHIGH confidence

invalid argument for nth_value function

What this means

SQLSTATE 22016 is raised when the NTH_VALUE window function receives a row offset argument that is not a positive integer.

Why it happens
  1. 1Calling NTH_VALUE with a zero, negative, or NULL row offset argument
How to reproduce

NTH_VALUE with a zero offset.

trigger — this will error
trigger — this will error
SELECT NTH_VALUE(salary, 0) OVER (ORDER BY salary) FROM employees;

expected output

ERROR:  argument 2 of nth_value must be greater than zero

Fix

Use a positive integer offset for NTH_VALUE

WHEN When the row position is computed dynamically.

Use a positive integer offset for NTH_VALUE
SELECT NTH_VALUE(salary, GREATEST(row_pos, 1)) OVER (ORDER BY salary)
FROM employees;

Why this works

GREATEST(row_pos, 1) clamps the offset to at least 1, preventing the 22016 error.

Sources
Official documentation ↗

Class 22 — Data Exception

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PostgreSQL errors