PG
PRO
22016ERRORTier 2 — Caution✅ HIGH confidence

invalid argument for nth_value function

Category: Data ExceptionVersions: All Postgres versions

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
SELECT NTH_VALUE(salary, 0) OVER (ORDER BY salary) FROM employees;
ERROR: argument 2 of nth_value must be greater than zero

Fix 1: Use a positive integer offset for NTH_VALUE

When the row position is computed dynamically.

fix
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 docs: https://www.postgresql.org/docs/current/errcodes-appendix.html

🔧 Source ref: Class 22 — Data Exception

Confidence assessment

✅ HIGH confidence

Standard SQLSTATE for window function argument validation. Stable across versions.

See also

📄 Reference pages

Window FunctionsNTH_VALUE
⚙️ This error reference was generated with AI assistance and reviewed for accuracy. Examples are provided to illustrate common scenarios and may not cover every case. Always test fixes in a development environment before applying to production. Spotted an error? Suggest a correction →