SQL error · GROUP BY and calculations

Aggregates cannot be nested

Problem: You are trying to compute a second summary over an aggregate at the same level.

Solution: Get the first summary in a subquery or CTE and apply the second aggregate from outside.

Why it happens: aggregates cannot be nested

Imagine you first want to add up how much each customer has spent and then average those per-customer figures. It is tempting to write one operation inside the other:

Problem pattern
SELECT AVG(SUM(total)) AS average_total_per_customer
FROM orders
GROUP BY customer_id;

On the local teaching database, SQLite rejects this query with misuse of aggregate function SUM(). Other engines show different messages, but the underlying problem is the same: SUM(total) already summarises several rows per customer, and AVG(...) tries to summarise those results without first creating a new intermediate result.

“Aggregates cannot be nested” error messages by engine

The exact wording depends on the database. Compare these common messages with the one in your console.

EngineTypical message
PostgreSQLERROR: aggregate function calls cannot be nested
MySQLERROR 1111 (HY000): Invalid use of group function
SQL ServerMsg 130, Level 15: Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
OracleORA-00935: group function is nested too deeply
SQLiteError: misuse of aggregate function SUM()

How to fix it in SQL

Portable fix: build the inner summary first

The most direct way is a subquery that produces one row per customer. The outer query can then average that new column:

Two levels with a subquery
SELECT ROUND(AVG(customer_total), 2) AS average_total_per_customer
FROM (
  SELECT customer_id,
         SUM(total) AS customer_total
  FROM orders
  GROUP BY customer_id
) AS by_customer;
Result verified locally on the teaching database
average_total_per_customer
393.19

The subquery handles the first level of detail: one row per customer_id. Afterwards, AVG(customer_total) receives ten rows that are already summarised and computes a single result.

The same separation with a CTE

If you want to make the sequence of calculations more visible, a CTE expresses the same idea with an intermediate name:

Two levels with a CTE
WITH totals_per_customer AS (
  SELECT customer_id,
         SUM(total) AS customer_total
  FROM orders
  GROUP BY customer_id
)
SELECT ROUND(AVG(customer_total), 2) AS average_total_per_customer
FROM totals_per_customer;

The CTE does not change the maths: it just makes the first stage explicit. It is especially handy if you later need to reuse the per-customer total in several expressions of the outer query.

How to check it

Run the inner summary on its own and review its rows before computing the outer average or sum.

How to avoid it next time

Each level of aggregation must correspond to a specific unit.

Related cases worth checking

Before adding a subquery, check whether the second aggregate is really needed

Not every nested aggregate asks a different question. For example, this query tries to add up each customer's order count:

Unnecessary nested aggregate
SELECT SUM(COUNT(*))
FROM orders
GROUP BY customer_id;

If all you want is the total number of orders, there is no need to count per customer and add them up again. The question comes down to:

Simpler form
SELECT COUNT(*) AS total_orders
FROM orders;
Result verified locally
total_orders
18

Separate stages when two different granularities are needed; simplify when the intermediate level adds no necessary information.

How it shows up on different engines

EngineRelevant behaviourPractical tip
PostgreSQL 18The documentation defines the argument of an aggregate expression as an expression that cannot contain another aggregate or a window function.Compute the inner aggregate in a subquery or CTE and aggregate outside it.
MySQL 8.4The official error reference includes error 1111, ER_INVALID_GROUP_FUNC_USE (“Invalid use of group function”), raised by invalid uses of group functions.Do not hide the problem by changing SQL modes: check the query level.
SQL ServerThe documentation for aggregate functions states that their expressions cannot contain other aggregate functions or subqueries in the argument.Materialise the inner summary first with a derived table or a CTE.
SQLiteReproducing AVG(SUM(total)) locally fails with misuse of aggregate function SUM().Use two levels here too; that keeps the structure portable and explicit.

The exact error text depends on the engine and the expression used. Do not memorise the message: recognise the pattern outer aggregate → inner aggregate at the same level.