MySQL “order by” inside of “group by”? Is it possible?

MySQLMySQLi Database

Instead of using ORDER BY inside GROUP BY, you can use the MAX() aggregate function.

The syntax is as follows −

SELECT yourNameColumnName,MAX(yourRankColumnName) FROM yourTableName
GROUP BY yourNameColumnName;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table MaxDemo
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(20),
   -> UserRank int
   -> );
Query OK, 0 rows affected (0.77 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into MaxDemo(UserName,UserRank) values('Larry',2);
Query OK, 1 row affected (0.21 sec)
mysql> insert into MaxDemo(UserName,UserRank) values('Sam',1);
Query OK, 1 row affected (0.17 sec)
mysql> insert into MaxDemo(UserName,UserRank) values('Sam',2);
Query OK, 1 row affected (0.15 sec)

Now you can display all records from the table using a select statement. The query is as follows −

mysql> select *from MaxDemo;

Output

+--------+----------+----------+
| UserId | UserName | UserRank |
+--------+----------+----------+
|      1 | Larry    |        2 |
|      2 | Sam      |        1 |
|      3 | Sam      |        2 |
+--------+----------+----------+
3 rows in set (0.00 sec)

Here is the query to use MAX() function to get your result −

mysql> select UserName,MAX(UserRank) from MaxDemo group by UserName;

Output

+----------+---------------+
| UserName | MAX(UserRank) |
+----------+---------------+
| Larry    |             2 |
| Sam      |             2 |
+----------+---------------+
2 rows in set (0.00 sec)
raja
Published on 19-Mar-2019 11:14:11
Advertisements