MySQL & MariaDB error 1111: Invalid use of group function
Invalid use of group function (5.6.51) An aggregate (SUM, COUNT, MAX, AVG...) is used where it can't be evaluated: in WHERE, in an UPDATE SET, or nested inside another aggregate. Move the condition to HAVING or use a derived table.
| MySQL | MariaDB | |
|---|---|---|
| Symbol | ER_INVALID_GROUP_FUNC_USE | ER_INVALID_GROUP_FUNC_USE |
| SQLSTATE | HY000 | HY000 |
| Type | Server error | Server error |
| Versions | every release since 5.0 active | every release since 5.5 active |
What it means
Aggregate functions work on a group of rows, which only exists after GROUP BY. WHERE filters single rows before grouping, so WHERE SUM(salary) > 100 asks for something that doesn’t exist yet.
Why it happens
- An aggregate in
WHERE:SELECT dept FROM emp WHERE SUM(salary) > 100 GROUP BY dept. - One aggregate inside another:
MAX(SUM(salary)). SQL evaluates one level of grouping per query block. - An aggregate in an
UPDATE … SET col = SUM(…)or in aJOIN … ONcondition.
How to fix it
- Filter groups with
HAVING:SELECT dept FROM emp GROUP BY dept HAVING SUM(salary) > 100. - For aggregates of aggregates, compute the inner one in a derived table:
SELECT MAX(total) FROM (SELECT SUM(salary) AS total FROM emp GROUP BY dept) d. On MySQL 8.0+ and MariaDB 10.2+ a CTE (WITH totals AS (…)) reads more clearly. - For
UPDATE, join to a derived table of totals:UPDATE dept d JOIN (SELECT dept, SUM(salary) s FROM emp GROUP BY dept) t ON t.dept = d.name SET d.total = t.s.
Reproduce it yourself
These steps are the exact test our harness runs. Use a scratch server, never production.
Connect with
mysql -u root -pand create a scratch database and the test data:CREATE DATABASE demo; USE demo; CREATE TABLE emp (dept VARCHAR(10), salary INT); INSERT INTO emp VALUES ('it',100),('it',200),('hr',50);Run:
SELECT dept FROM emp WHERE SUM(salary) > 100 GROUP BY dept;
You get: Invalid use of group function(11.8.9)
Verified fixes
Filter on aggregates with HAVING
SELECT dept FROM emp GROUP BY dept HAVING SUM(salary) > 100;Aggregate in a derived table, then aggregate again outside it
SELECT MAX(total) FROM (SELECT SUM(salary) AS total FROM emp GROUP BY dept) d;
Tested on
| Step | MySQL | MariaDB | |||||||
|---|---|---|---|---|---|---|---|---|---|
| 5.6 | 5.7 | 8.0 | 8.4 | 9 | 10.6 | 10.11 | 11.4 | 11.8 | |
| An aggregate (SUM, COUNT, MAX...) in the WHERE clause repro | ✓ 1111 | ✓ 1111 | ✓ 1111 | ✓ 1111 | ✓ 1111 | ✓ 1111 | ✓ 1111 | ✓ 1111 | ✓ 1111 |
| One aggregate nested inside another version check | ✓ 1111 | ✓ 1111 | ✓ 1111 | ✓ 1111 | ✓ 1111 | ✓ 1111 | ✓ 1111 | ✓ 1111 | ✓ 1111 |
| Filter on aggregates with HAVING fix | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
| Aggregate in a derived table, then aggregate again outside it fix | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |