sqlstreak

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.

Broken
SELECT name, age
FROM pets
HAVING age > 5;
Fixed
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

nameage
Ziggy6
Pickles7
Socks8
Bruno9
Gizmo10
Tofu11

The fix returns, SQLite: 6 rows

nameage
Ziggy6
Pickles7
Socks8
Bruno9
Gizmo10
Tofu11

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

speciespets
cat7
dog8

Returns, SQLite: 2 rows

speciespets
cat7
dog8

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.