How to fetch a specific row when values are the same in MySQL?


To fetch a specific row when values are the same, use GROUP BY. Let us first create a table −

mysql> create table DemoTable659(Id int,Name varchar(100),Score int);
Query OK, 0 rows affected (0.52 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable659 values(11,'John',45);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable659 values(15,'John',59);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable659 values(15,'Sam',61);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable659;

This will produce the following output −

+------+------+-------+
| Id   | Name | Score |
+------+------+-------+
|   11 | John |    45 |
|   15 | John |    59 |
|   15 | Sam  |    61 |
+------+------+-------+
3 rows in set (0.00 sec)

Here is the query to fetch a specific row when values are the same −

mysql> select *from ( select *from DemoTable659 order by Id desc) tbl group by Name;

This will produce the following output −

+------+------+-------+
| Id   | Name | Score |
+------+------+-------+
|   11 | John | 45    |
|   15 | Sam  | 61    |
+------+------+-------+
2 rows in set (0.04 sec)

Updated on: 23-Aug-2019

39 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements