Skip to content
Advertisement

Mysql SQL syntax group by [asc|desc]?

In using mysql8.0 it gives the GROUP BY syntax as the following:

[GROUP BY {col_name | expr | position}
  [ASC | DESC], ... [WITH ROLLUP]]

What is the usage of the asc or desc in the group by? Every time I try something like that I get a syntax error and have never seen that syntax before, so was curious what its usage is an what an example of it might be. A query I was using for testing was:

SELECT 
    provider_id,
    COUNT(*)
FROM
    titles
GROUP BY
    provider_id,         -- a col_name
    provider_id='Fox',   -- an expression
    1                    -- a position
    -- where does the ASC|DESC come into play?
    WITH ROLLUP          -- using rollup
ORDER BY COUNT(*) DESC

Advertisement

Answer

MySQL 8.0 Reference Manual / … / SELECT Statement

Prior to MySQL 8.0.13, MySQL supported a nonstandard syntax extension that permitted explicit ASC or DESC designators for GROUP BY columns. MySQL 8.0.12 and later supports ORDER BY with grouping functions so that use of this extension is no longer necessary. (Bug #86312, Bug #26073525) This also means you can sort on an arbitrary column or columns when using GROUP BY, like this:

SELECT a, b, COUNT(c) AS t FROM test_table GROUP BY a,b ORDER BY a,t DESC;

As of MySQL 8.0.13, the GROUP BY extension is no longer supported: ASC or DESC designators for GROUP BY columns are not permitted.

In earlier versions the GROUP BY expression causes implicit ORDER BY by the same expression (until explicit ORDER BY clause specified) – and [ASC|DESC] allows to manipulate this implicit sorting. Now only explicit sorting is allowed.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement