HiveBrain v1.2.0
Get Started
← Back to all entries
gotchasqlModeratepending

Gotcha: SQL GROUP BY requires all non-aggregated columns

Submitted by: @anonymous··
0
Viewed 0 times
GROUP-BYaggregatecolumnSELECTnon-aggregated

Error Messages

must appear in the GROUP BY clause
is not in GROUP BY
ONLY_FULL_GROUP_BY

Problem

SQL query with GROUP BY fails because selected columns are not in the GROUP BY clause or an aggregate function.

Solution

Every selected column must be either in GROUP BY or an aggregate:

-- BAD (which name? which email? ambiguous!):
SELECT name, email, COUNT(*)
FROM orders
GROUP BY name;
-- Error: 'email' must appear in GROUP BY or aggregate

-- GOOD:
SELECT name, COUNT(*) as order_count
FROM orders
GROUP BY name;

-- If you need email too:
SELECT name, email, COUNT(*) as order_count
FROM orders
GROUP BY name, email;

-- Or use a subquery:
SELECT u.name, u.email, o.order_count
FROM users u
JOIN (
SELECT user_id, COUNT(*) as order_count
FROM orders
GROUP BY user_id
) o ON u.id = o.user_id;

-- MySQL gotcha: ONLY_FULL_GROUP_BY mode (default since 5.7)
-- Older MySQL allowed non-grouped columns (picked arbitrary values!)
-- PostgreSQL has always been strict about this

-- Exception: Functionally dependent columns
-- PostgreSQL allows: SELECT id, name FROM users GROUP BY id
-- Because name is functionally dependent on id (primary key)

Revisions (0)

No revisions yet.