Set sort order on group by in MySql

Problem: When using GROUP BY in MySql you don’t really have control over which item will be selected in the result set (and using ORDER BY in your main query won’t help due to the processing order). You also are limited to a single value.

Answer: Use MIN or MAX in your select statement. For example in a case where you had a bunch of days grouped by some attribute and you wanted to find both the first and last date, you can use something like:

SELECT...
MIN(my_days.date) AS start_date, 
MAX(my_days.date) AS end_date,
...
GROUP BY...

Leave a Reply