sqlstreak

SQL error

window functions are not allowed in WHERE

Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)

Short answer

Window functions are computed after WHERE, so you can't filter on them directly. Compute the window function in a subquery or CTE, then filter in the outer query.

The exact messages

  • PostgreSQLERROR: window functions are not allowed in WHERE
  • SQLitemisuse of window function ROW_NUMBER()

How to read this message

This is what PostgreSQL 18.6 prints for the broken query below, the way psql shows it. LINE gives the line it was reading when it gave up, and the ^ marks the exact spot.

ERROR:  window functions are not allowed in WHERE
LINE 2: WHERE ROW_NUMBER() OVER (ORDER BY price DESC) = 1;
              ^

SQLite 3.54.1 reports the same mistake as misuse of window function ROW_NUMBER(), with no line number: look for the word or column it names.

Why it happens

Keeping the top row per group

WHERE ROW_NUMBER() OVER (...) = 1 is the most common attempt. Wrap it instead.

Filtering on LAG or a running total

Same rule: compute it in an inner query, filter outside.

Reproduce it, then fix it

Both queries run on a real database in your browser. Switch dialects to compare.

Broken
SELECT name FROM menu_items
WHERE ROW_NUMBER() OVER (ORDER BY price DESC) = 1;
Fixed
SELECT name, price
FROM (SELECT name, price,
  ROW_NUMBER() OVER (ORDER BY price DESC) AS rn
  FROM menu_items) t
WHERE rn = 1;

The inner query numbers the rows; the outer query can then filter on that number like any column.

The fix returns, PostgreSQL: 1 row

nameprice
BBQ Meteor15.5

The fix returns, SQLite: 1 row

nameprice
BBQ Meteor15.5

Experiment with it: PostgreSQL playground·SQLite playground

Official documentation

Stop hitting this error

Practise the concept behind it in a five-minute lesson, or read the full guide: SQL window functions.