# HAVING clause on a non-aggregate query (SQLite)

Source: https://sqlstreak.com/sql/errors/having-clause-on-a-non-aggregate-query · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


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

- PostgreSQL: `ERROR: column "pets.name" must appear in the GROUP BY clause or be used in an aggregate function`
- SQLite: `HAVING clause on a non-aggregate query`

## How PostgreSQL prints it

```
ERROR:  column "pets.name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT name, age
               ^
```

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

## The broken query

```sql
SELECT name, age
FROM pets
HAVING age > 5;
```

## The fix

```sql
SELECT name, age
FROM pets
WHERE age > 5
ORDER BY age;
```

A condition on each row belongs in WHERE.

| name | age |
| --- | --- |
| Ziggy | 6 |
| Pickles | 7 |
| Socks | 8 |
| Bruno | 9 |
| Gizmo | 10 |
| Tofu | 11 |
