42P20
PostgreSQLERRORNotableSyntax Error or Access Rule ViolationHIGH confidence

windowing error

What this means

SQLSTATE 42P20 is a Postgres-specific error raised when a window function definition or window frame specification is semantically invalid — for example, nesting window functions or using a window function in an invalid context.

Why it happens
  1. 1Nesting a window function inside another window function call
  2. 2Using a window function in a WHERE or GROUP BY clause (window functions can only appear in SELECT and ORDER BY)
  3. 3Window function OVER clause with contradictory or invalid frame options
How to reproduce

Window function in an invalid context.

trigger — this will error
trigger — this will error
SELECT * FROM employees WHERE ROW_NUMBER() OVER (ORDER BY id) = 1;
-- window function in WHERE clause

expected output

ERROR:  window functions are not allowed in WHERE

Fix

Move window function to the SELECT list and filter in a CTE or subquery

WHEN When filtering on a window function result.

Move window function to the SELECT list and filter in a CTE or subquery
SELECT * FROM (
  SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS rn
  FROM employees
) sub WHERE rn = 1;

Why this works

Window functions are evaluated after WHERE, so they must be computed in an inner query first, then filtered in an outer WHERE.

What not to do

Use a window function in WHERE, GROUP BY, or HAVING

Window functions are only valid in SELECT and ORDER BY clauses — they must be placed in a subquery for further filtering.

Sources
Official documentation ↗

Class 42 — Syntax Error or Access Rule Violation (Postgres-specific)

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

← All PostgreSQL errors