MySQL : isn't in GROUP BY MySQL : isn't in GROUP BY sql sql

MySQL : isn't in GROUP BY


You need to have a full group by:

SELECT `name`, `type`, `language`, `code` FROM `users` WHERE `verified` = '1' GROUP BY `name`, `type`, `language`, `code` ORDER BY `count` DESC LIMIT 0, 25

SQL92 requires that all columns (except aggregates) in the select clause is part of the group by clause. SQL99 loosens this restriction a bit and states that all columns in the select clause must be functionally dependent of the group by clause. MySQL by default allows for partial group by and this may produce non-deterministic answers, example:

create table t (x int, y int);insert into t (x,y) values (1,1),(1,2),(1,3);select x,y from t group by x;+------+------+| x    | y    |+------+------+|    1 |    1 |+------+------+

I.e. a random y is select for the group x. One can prevent this behavior by setting @@sql_mode:

set @@sql_mode='ONLY_FULL_GROUP_BY';select x,y from t group by x; ERROR 1055 (42000): 'test.t.y' isn't in GROUP BY


The best solution to this problem is, of course, using a complete GROUP BY expression.

But there's another solution that works around the ONLY_FULL_GROUP_BY blocking of the old MySQL extension to GROUP BY.

SELECT name,        ANY_VALUE(type) type,       ANY_VALUE(language) language,       ANY_VALUE(code) code   FROM users   WHERE verified = '1'  GROUP BY name  ORDER BY count DESC LIMIT 0, 25

ANY_VALUE() explicitly declares what used to be implicit in MySQL's incomplete GROUP BY operations -- that the server can choose, well, any, value to return.


Another solution mentioned multiple times above is to turn off that annoying 'ONLY_FULL_GROUP_BY' e.g. like in this post:Disable ONLY_FULL_GROUP_BY

I think this solution is very useful if you do not want to refactor the whole project for multiple hours. And if you do not care about the unpredictable values of the columns which are not list of the GROUP BY.