SQL error
aggregate 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
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
- PostgreSQLERROR: aggregate functions are not allowed in WHERE
- SQLitemisuse of aggregate function AVG()
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: aggregate functions are not allowed in WHERE
LINE 2: WHERE price > AVG(price);
^SQLite 3.54.1 reports the same mistake as misuse of aggregate function AVG(), with no line number: look for the word or column it names.
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.
Reproduce it, then fix it
Both queries run on a real database in your browser. Switch dialects to compare.
SELECT name FROM menu_items
WHERE price > AVG(price);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.
The fix returns, PostgreSQL: 5 rows
| name | price |
|---|---|
| Margherita | 11 |
| Pepperoni Rocket | 13.5 |
| Four Cheese Orbit | 14 |
| BBQ Meteor | 15.5 |
| Veggie Nebula | 13 |
The fix returns, SQLite: 5 rows
| name | price |
|---|---|
| Margherita | 11 |
| Pepperoni Rocket | 13.5 |
| Four Cheese Orbit | 14 |
| BBQ Meteor | 15.5 |
| Veggie Nebula | 13 |
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 subqueries.