How to order or choose rows in MySQL GROUP BY clause?


Let us first create a table −

mysql> create table DemoTable1572
   -> (
   -> StudentId int,
   -> StudentMarks int,
   -> StudentName varchar(20)
   -> );
Query OK, 0 rows affected (0.56 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1572 values(1,79,'Sam');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1572 values(2,89,'Chris');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1572 values(3,98,'David');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable1572 values(4,79,'Bob');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1572;

This will produce the following output −

+-----------+--------------+-------------+
| StudentId | StudentMarks | StudentName |
+-----------+--------------+-------------+
|         1 |           79 |       Sam   |
|         2 |           89 |       Chris |
|         3 |           98 |       David |
|         4 |           79 |       Bob   |
+-----------+--------------+-------------+
4 rows in set (0.00 sec)

Here is the query to order or choose rows in MySQL GROUP BY clause −

mysql> select * from DemoTable1572
   -> where StudentId in (select min(StudentId) from DemoTable1572 group by StudentMarks);

This will produce the following output −

+-----------+--------------+-------------+
| StudentId | StudentMarks | StudentName |
+-----------+--------------+-------------+
|         1 |           79 |       Sam   |
|         2 |           89 |       Chris |
|         3 |           98 |       David |
+-----------+--------------+-------------+
3 rows in set (0.10 sec)

Updated on: 16-Dec-2019

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements