# window functions are not allowed in WHERE

Source: https://sqlstreak.com/sql/errors/window-functions-not-allowed-in-where · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**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

- PostgreSQL: `ERROR: window functions are not allowed in WHERE`
- SQLite: `misuse of window function ROW_NUMBER()`

## How PostgreSQL prints it

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

## 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.

## The broken query

```sql
SELECT name FROM menu_items
WHERE ROW_NUMBER() OVER (ORDER BY price DESC) = 1;
```

## The fix

```sql
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.

| name | price |
| --- | --- |
| BBQ Meteor | 15.5 |
