What's the Default Ordering of MySQL GROUP BY Clause?

By default, the MySQL GROUP BY clause orders the result in ascending order. To demonstrate this, let's suppose you have the following table:

CREATE TABLE user (
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(25) NOT NULL,
    PRIMARY KEY (id)
);

INSERT INTO user(name)
VALUES ('john'), ('david'), ('john'), ('john'), ('wayne'), ('david');

If you run the SELECT statement on this table, you will see the following output:

+----+--------+
| id |  name  |
+----+--------+
|  1 |  john  |
|  2 |  david |
|  3 |  john  |
|  4 |  john  |
|  5 |  wayne |
|  6 |  david |
+----+--------+

When you add the GROUP BY clause to the SELECT statement, you will see that the result is sorted in ascending order based on the values in the grouped column:

SELECT *
FROM user
GROUP BY name

This would result in the following:

+----+--------+
| id |  name  |
+----+--------+
|  2 |  david |
|  1 |  john  |
|  5 |  wayne |
+----+--------+

Hope you found this post useful. It was published . Please show your love and support by sharing this post.