Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does MySQL decide which id to return in group by clause?

Tags:

mysql

group-by

Such as this one:

SELECT id, count( * ) , company FROM jobs GROUP BY company

Where id is the primary key of jobs

like image 676
omg Avatar asked Dec 31 '25 16:12

omg


1 Answers

Similar question:

Why does MySQL allow "group by" queries WITHOUT aggregate functions?

This is MySQL specific, and is not ANSI standard SQL. Most other database engines do not allow columns on which is not being grouped or being run through an aggregate function.

It seems MySQL retains the value of the first row that matches the criteria.

The aggregate function that has this behaviour is FIRST(), and although MySQL implements it, this seems to be default behaviour for columns that are not grouped on, and which are not run through any other aggregate function.

In ANSI standard SQL you would do:

SELECT FIRST(jobtitle), company FROM jobs GROUP BY company;

Whereas in MySQL you could just (however the ANSI standard works just aswell):

SELECT jobtitle, company FROM jobs GROUP BY company;
like image 108
Yannick Motton Avatar answered Jan 03 '26 10:01

Yannick Motton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!