SQL error
HAVING clause on a non-aggregate query (SQLite)
Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)
Short answer
HAVING filters groups, so it needs a grouped query: a GROUP BY or an aggregate in SELECT. To filter single rows, use WHERE; to filter groups, add GROUP BY and test an aggregate in HAVING.
The exact messages
- PostgreSQLERROR: column "pets.name" must appear in the GROUP BY clause or be used in an aggregate function
- SQLiteHAVING clause on a non-aggregate query
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: column "pets.name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT name, age
^SQLite 3.54.1 reports the same mistake as HAVING clause on a non-aggregate query, with no line number: look for the word or column it names.
Why it happens
HAVING used instead of WHERE
SELECT name FROM pets HAVING age > 5 means “pets older than 5”: a row filter, so WHERE.
A missing GROUP BY
You meant “species with more than 3 pets” but forgot to group. Add GROUP BY species and use HAVING COUNT(*) > 3.
Reproduce it, then fix it
Both queries run on a real database in your browser. Switch dialects to compare.
SELECT name, age
FROM pets
HAVING age > 5;SELECT name, age
FROM pets
WHERE age > 5
ORDER BY age;A condition on each row belongs in WHERE.
The fix returns, PostgreSQL: 6 rows
| name | age |
|---|---|
| Ziggy | 6 |
| Pickles | 7 |
| Socks | 8 |
| Bruno | 9 |
| Gizmo | 10 |
| Tofu | 11 |
The fix returns, SQLite: 6 rows
| name | age |
|---|---|
| Ziggy | 6 |
| Pickles | 7 |
| Socks | 8 |
| Bruno | 9 |
| Gizmo | 10 |
| Tofu | 11 |
Experiment with it: PostgreSQL playground·SQLite playground
Another fix
A condition on groups: group first, then HAVING tests the aggregate.
SELECT species, COUNT(*) AS pets
FROM pets
GROUP BY species
HAVING COUNT(*) > 3;Returns, PostgreSQL: 2 rows
| species | pets |
|---|---|
| cat | 7 |
| dog | 8 |
Returns, SQLite: 2 rows
| species | pets |
|---|---|
| cat | 7 |
| dog | 8 |
Official documentation
Stop hitting this error
Practise the concept behind it in a five-minute lesson, or read the full guide: SQL GROUP BY and HAVING.