undefined
undefined

Reputation: 2101

MySQL GROUP BY and ORDER BY order

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?

Upvotes: 2

Views: 256

Answers (3)

Vikram Jain
Vikram Jain

Reputation: 5588

  • First WHERE condition
  • Second GROUP BY
  • Third one is ORDER BY

Example :

SELECT * FROM table GROUP BY columnanme ORDER BY columnanmae

Upvotes: 1

John Woo
John Woo

Reputation: 263703

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

Upvotes: 8

GregD
GregD

Reputation: 2867

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.

Upvotes: 0

Related Questions