Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Group By with an Order By

People also ask

Can you have a GROUP BY and ORDER BY in SQL?

Order By and Group By Clause in SQLGroup By in SQL is used to arrange similar data into groups and Order By in SQL is used to sort the data in ascending or descending order.

Can we use GROUP BY and ORDER BY and having in same query?

GROUP BY and ORDER BY can be used in the same query and it is NOT required that they be the same column. GROUP BY controls the way the data is organized for sumarization. ORDER BY simply sorts the rows of the result.

Does ORDER BY go after GROUP BY?

In the query, GROUP BY clause is placed after the WHERE clause. In the query, GROUP BY clause is placed before ORDER BY clause if used any.


In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias:

SELECT COUNT(id) AS theCount, `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY theCount DESC
LIMIT 20

MySQL prior to version 5 did not allow aggregate functions in ORDER BY clauses.

You can get around this limit with the deprecated syntax:

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY 1 DESC
LIMIT 20

1, since it's the first column you want to group on.


I don't know about MySQL, but in MS SQL, you can use the column index in the order by clause. I've done this before when doing counts with group bys as it tends to be easier to work with.

So

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20

Becomes

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER 1 DESC
LIMIT 20

In Oracle, something like this works nicely to separate your counting and ordering a little better. I'm not sure if it will work in MySql 4.

select 'Tag', counts.cnt
from
  (
  select count(*) as cnt, 'Tag'
  from 'images-tags'
  group by 'tag'
  ) counts
order by counts.cnt desc