# aggregate function calls cannot be nested / misuse of aggregate function COUNT()

Source: https://sqlstreak.com/sql/errors/aggregate-function-calls-cannot-be-nested · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


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

- PostgreSQL: `ERROR: aggregate function calls cannot be nested`
- SQLite: `misuse of aggregate function COUNT()`

## How PostgreSQL prints it

```
ERROR:  aggregate function calls cannot be nested
LINE 1: SELECT AVG(COUNT(*)) AS avg_lines
                   ^
```

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

## The broken query

```sql
SELECT AVG(COUNT(*)) AS avg_lines
FROM order_items
GROUP BY order_id;
```

## The fix

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

| avg_lines_per_order |
| --- |
| 1.88 |
