Only display row with highest ID in MySQL


To order, use the ORDER BY DESC clause. With that, since we want a single ID, which should be the highest, use LIMIT 1. This will fetch the row with highest ID. Let us first create a table −

mysql> create table DemoTable
(
   Id int,
   FirstName varchar(50)
);
Query OK, 0 rows affected (0.83 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(110,'Robert');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(120,'Mike');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(115,'Bob');
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 100  | Chris     |
| 110  | Robert    |
| 120  | Mike      |
| 115  | Bob       |
+------+-----------+
4 rows in set (0.00 sec)

Following is the query to display row with highest ID −

mysql> select *from DemoTable order by Id DESC LIMIT 1;

This will produce the following output −

+------+-----------+
| Id   | FirstName |
+------+-----------+
| 120  | Mike      |
+------+-----------+
1 row in set (0.00 sec)

Updated on: 03-Oct-2019

98 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements