When executing a query with GROUP BY and ORDER BY,
Which part runs first?
Does the ORDER BY take affect after the results are grouped or will the result row show the
result with the highest(DESC) ORDER BY value?
I want the order by to sort the results first and then group by...
Asked
Active
Viewed 25 times
0
Asaf Maoz
- 626
- 2
- 6
- 20
-
The `group by` logically and practically runs first. The `order by` is on the results of the aggregation. – Gordon Linoff Aug 03 '14 at 14:32
-
Tnx for that, so if I want to order the results and then aggregate the results? what can I do? – Asaf Maoz Aug 03 '14 at 14:37
-
Why would you want to order the results before aggregation? It would help if you show your table setup, a query and example output, and what you'd like it to be. – Andomar Aug 03 '14 at 14:53
-
I want to get the oldest record and group by the user_id, got my answer here: http://stackoverflow.com/questions/14770671/mysql-order-by-before-group-by – Asaf Maoz Aug 03 '14 at 14:54
-
@AsafMaoz . . . There is no reason why you want to order the results before a `group by`. It sounds like you want to use a MySQL extension to `group by`, where columns in the `select` are not in the `group by`. However, that is explicitly discouraged: http://dev.mysql.com/doc/refman/5.7/en/group-by-extensions.html. – Gordon Linoff Aug 03 '14 at 17:24
-
In the link I provided there is a usage example similar to what I needed: "The task in this instance is to get the latest post for each author in the database." – Asaf Maoz Aug 04 '14 at 10:04