SQL error
aggregate function calls cannot be nested / misuse of aggregate function COUNT()
Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)
Short answer
You can't put one aggregate inside another, like AVG(COUNT(*)) or SUM(MAX(x)), at the same level of a query. Aggregate once in a subquery or CTE, then aggregate that result in the outer query.
The exact messages
- PostgreSQLERROR: aggregate function calls cannot be nested
- SQLitemisuse of aggregate function COUNT()
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 function calls cannot be nested
LINE 1: SELECT AVG(COUNT(*)) AS avg_lines
^SQLite 3.54.1 reports the same mistake as misuse of aggregate function COUNT(), with no line number: look for the word or column it names.
Why it happens
Averaging per-group counts in one step
“The average number of lines per order” needs two levels: first one row per order with its count, then the average over those rows. AVG(COUNT(*)) tries to do both at once.
Counting the groups themselves
COUNT(COUNT(*)) to count categories is the same mistake. Count in an outer query, or use COUNT(DISTINCT category) without grouping.
You wanted a total beside each group
To show each group's count next to the grand total, a window function over the grouped rows is allowed: SUM(COUNT(*)) OVER () (see the second fix).
Reproduce it, then fix it
Both queries run on a real database in your browser. Switch dialects to compare.
SELECT AVG(COUNT(*)) AS avg_lines
FROM order_items
GROUP BY order_id;SELECT ROUND(AVG(lines), 2) AS avg_lines_per_order
FROM (SELECT order_id, COUNT(*) AS lines
FROM order_items
GROUP BY order_id) per_order;The subquery makes one row per order with its line count; the outer query averages those counts. A CTE (WITH per_order AS (…)) does the same and reads top to bottom.
The fix returns, PostgreSQL: 1 row
| avg_lines_per_order |
|---|
| 1.88 |
The fix returns, SQLite: 1 row
| avg_lines_per_order |
|---|
| 1.88 |
Experiment with it: PostgreSQL playground·SQLite playground
Another fix
A window function runs after grouping, so it may wrap an aggregate: each category's count sits beside the total of all counts.
SELECT category, COUNT(*) AS items,
SUM(COUNT(*)) OVER () AS all_items
FROM menu_items
GROUP BY category;Returns, PostgreSQL: 4 rows
| category | items | all_items |
|---|---|---|
| drink | 2 | 11 |
| dessert | 1 | 11 |
| pizza | 5 | 11 |
| side | 3 | 11 |
Returns, SQLite: 4 rows
| category | items | all_items |
|---|---|---|
| dessert | 1 | 11 |
| drink | 2 | 11 |
| pizza | 5 | 11 |
| side | 3 | 11 |
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.