How to get the data associated with the maximum id in a MySQL table?



We will first order by DESC and then fetch the value associated with maximum id −

select *from yourTableName order by yourColumnName DESC LIMIT 1,1;

Let us first create a table −

mysql> create table DemoTable    -> (    -> Alldata int    -> ); Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(303); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(560); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(490); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(498); Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+---------+ | Alldata | +---------+ |     303 | |     560 | |     100 | |     490 | |     498 | +---------+ 5 rows in set (0.00 sec)

Following is the query to get the record associated with the maximum id −

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

Output

+---------+ | Alldata | +---------+ |     498 | +---------+ 1 row in set (0.00 sec)
Updated on: 2019-07-30T22:30:26+05:30

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements