PostgreSQL GROUP BY different from MySQL?

MySQL’s totally non standards compliant GROUP BY can be emulated by Postgres’ DISTINCT ON. Consider this:

MySQL:

SELECT a,b,c,d,e FROM table GROUP BY a

This delivers 1 row per value of a (which one, you don’t really know). Well actually you can guess, because MySQL doesn’t know about hash aggregates, so it will probably use a sort… but it will only sort on a, so the order of the rows could be random. Unless it uses a multicolumn index instead of sorting. Well, anyway, it’s not specified by the query.

Postgres:

SELECT DISTINCT ON (a) a,b,c,d,e FROM table ORDER BY a,b,c

This delivers 1 row per value of a, this row will be the first one in the sort according to the ORDER BY specified by the query. Simple.

Note that here, it’s not an aggregate I’m computing. So GROUP BY actually makes no sense. DISTINCT ON makes a lot more sense.

Rails is married to MySQL, so I’m not surprised that it generates SQL that doesn’t work in Postgres.

Leave a Comment