MySql how to display the records with latest ID in a table?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable676(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Number int
);
Query OK, 0 rows affected (0.50 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable676(Number) values(1000);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable676(Number) values(1839);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable676(Number) values(29894);
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable676(Number) values(1264);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable676(Number) values(190);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable676(Number) values(167);
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable676;

This will produce the following output −

+----+--------+
| Id | Number |
+----+--------+
|  1 | 1000   |
|  2 | 1839   |
|  3 | 29894  |
|  4 | 1264   |
|  5 | 190    |
|  6 | 167    |
+----+--------+
6 rows in set (0.00 sec)

Following is the query to display the records with latest id number in a table −

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

This will produce the following output −

+----+--------+
| Id | Number |
+----+--------+
|  6 | 167    |
+----+--------+
1 row in set (0.00 sec)
raja
Published on 26-Aug-2019 10:23:39
Advertisements