window in WHERE 🗃️ SQL

ERROR: window functions are not allowed in WHERE

A window function (ROW_NUMBER, RANK, LAG) was filtered directly in WHERE.

Seen on: SQL

Meaning

Window functions are computed after WHERE/GROUP BY. Filter on them in an outer query or CTE (or QUALIFY in some engines).

Common causes

  • WHERE ROW_NUMBER() OVER (...) = 1
  • Window results referenced in WHERE/HAVING

⚡ Quick fix

  1. Compute in a CTE/subquery and filter outside
  2. Use QUALIFY where supported (Snowflake, BigQuery, DuckDB)

Detailed fix by platform

SQL

  1. WITH r AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) rn FROM orders) SELECT * FROM r WHERE rn = 1;

How to diagnose

  1. Clause — Window function in WHERE?
  2. Recent change — Did it start after a deploy, upgrade, or configuration change? Compare with the last working version.

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.