1962
MariaDBERRORNotableQueryHIGH confidence

Non-grouping field is used in HAVING clause

Production Risk

Medium — incorrect GROUP BY queries produce non-deterministic results.

What this means

A column referenced in a HAVING clause is not an aggregate expression and is not listed in the GROUP BY clause. This violates SQL standard group-by semantics enforced by ONLY_FULL_GROUP_BY mode.

Why it happens
  1. 1HAVING clause references a non-aggregated column not present in GROUP BY.
  2. 2sql_mode includes ONLY_FULL_GROUP_BY (the default in MySQL 5.7+).
How to reproduce
trigger — this will error
trigger — this will error
SELECT dept, salary FROM emp GROUP BY dept HAVING salary > 5000;

expected output

ERROR 1962 (HY000): Non-grouping field 'salary' is used in HAVING clause.

Fix

Use an aggregate function in HAVING

Use an aggregate function in HAVING
SELECT dept, AVG(salary) FROM emp GROUP BY dept HAVING AVG(salary) > 5000;

Why this works

HAVING must reference either grouping columns or aggregate expressions.

What not to do

Version notes

Sources
Official documentation ↗

MySQL 8.0 — 1962 ER_NON_GROUPING_FIELD_USED

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All MariaDB errors