Diagnostic Queries
Symptoms
A window function (using OVER) was used in a WHERE clause. Window functions run after WHERE, so PostgreSQL raises SQLSTATE 42P20 (windowing_error).
- A function with OVER appears in WHERE/GROUP BY/HAVING.
- Window functions execute after rows are selected and grouped.
- Common when filtering on a
row_number()/rank().
What the server log shows
ERROR: window functions are not allowed in WHERE
LINE 1: ...SELECT * FROM t WHERE row_number() OVER (ORDER BY id) <= 10
Why PostgreSQL raises this — what the manual says
Section 3.5 Window Functions:
“They are forbidden elsewhere, such as in GROUP BY, HAVING and WHERE clauses.”
Window functions compute over the result set after WHERE, GROUP BY, and HAVING have been applied. Their values do not exist when WHERE runs, so PostgreSQL rejects them there with 42P20.
Common causes
- Filtering directly on a window function result in WHERE.
- Trying to keep top-N rows with a window function in WHERE.
- Confusing window evaluation order with row filtering.
How to fix it
- Wrap the window function in a subquery/CTE, then filter in the outer query.
- Example:
SELECT * FROM (SELECT *, row_number() OVER (ORDER BY id) rn FROM t) s WHERE rn <= 10;. - Use
LIMIT/FETCHfor simple top-N without window functions.
Related & next steps
Reference: PostgreSQL 18 Section 3.5 “Window Functions”.
Thanks — noted. This helps keep the database accurate.