2

Does it matter which comes after which? I mean if I do

SELECT * FROM  table GROUP BY x ORDER BY y

will the results first be grouped and then ordered?

John Woo
  • 258,903
  • 69
  • 498
  • 492
undefined
  • 2,051
  • 3
  • 26
  • 47

3 Answers3

8

ORDER is the last clause to be executed.

The order of execution

  • FROM clause
  • WHERE clause (the reason why you can't use alias on this clause)
  • GROUP BY clause
  • HAVING clause
  • SELECT clause
  • ORDER BY clause

For more info, please click here

John Woo
  • 258,903
  • 69
  • 498
  • 492
1
  • First WHERE condition
  • Second GROUP BY
  • Third one is ORDER BY

Example :

SELECT * FROM table GROUP BY columnanme ORDER BY columnanmae
Tom Seidel
  • 9,525
  • 1
  • 26
  • 38
Vikram Jain
  • 5,498
  • 1
  • 19
  • 31
0

In MySQL, a GROUP BY clause has the side effect of sorting columns as well. If you already have a GROUP BY clause in your query that produces the desired sort order, there's no need for an ORDER BY.

GregD
  • 2,797
  • 3
  • 28
  • 39