Display first selected row in MySQL?


You can use ORDER BY for this. Let us first create a table −

mysql> create table DemoTable
   (
   Value int
   );
Query OK, 0 rows affected (0.20 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable values(8);
Query OK, 1 row affected (0.09 sec)

mysql> insert into DemoTable values(18);
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable values(11);
Query OK, 1 row affected (0.09 sec)

mysql> insert into DemoTable values(9);
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable values(19);
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable values(6);
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable values(7);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
| 20    |
| 8     |
| 18    |
| 11    |
| 9     |
| 19    |
| 6     |
| 7     |
+-------+
8 rows in set (0.00 sec)

Following is the query to display first selected row in MySQL −

mysql> select *from DemoTable order by (Value=9) DESC,Value DESC;

This will produce the following output −

+-------+
| Value |
+-------+
| 9     |
| 20    |
| 19    |
| 18    |
| 11    |
| 8     |
| 7     |
| 6     |
+-------+
8 rows in set (0.00 sec)

Updated on: 30-Jul-2019

132 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements