# aggregate functions are not allowed in WHERE

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


**Short answer:** `WHERE` filters individual rows before any grouping, so it can't use `AVG`, `SUM` or `COUNT`. Use `HAVING` to filter groups, or compare against a subquery that computes the aggregate.

## The exact messages

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

## How PostgreSQL prints it

```
ERROR:  aggregate functions are not allowed in WHERE
LINE 2: WHERE price > AVG(price);
                      ^
```

## Why it happens

### Comparing each row to an overall average

“Items priced above average” needs the average first: put it in a subquery.

### Filtering groups

“Categories with more than 3 items” is a group filter: `GROUP BY category HAVING COUNT(*) > 3`.

## The broken query

```sql
SELECT name FROM menu_items
WHERE price > AVG(price);
```

## The fix

```sql
SELECT name, price FROM menu_items
WHERE price > (SELECT AVG(price) FROM menu_items);
```

The subquery runs first and returns a single number, which every row can then be compared with.

| name | price |
| --- | --- |
| Margherita | 11 |
| Pepperoni Rocket | 13.5 |
| Four Cheese Orbit | 14 |
| BBQ Meteor | 15.5 |
| Veggie Nebula | 13 |
