How can I select the row with the highest ID in MySQL?

MySQLMySQLi Database

You can select the row with highest ID in MySQL with the help of ORDER BY with LIMIT OFFSET

The syntax is as follows −

select *from yourTableName order by yourColumnName desc limit 1 offset 0;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table HighestIdOrderBy
   −> (
   −> EmployeeId int,
   −> EmployeeName varchar(200)
   −> );
Query OK, 0 rows affected (0.58 sec)

Insert records in the table with the help of insert command. The query is as follows −

mysql> insert into HighestIdOrderBy values(200,'David');
Query OK, 1 row affected (0.20 sec)

mysql> insert into HighestIdOrderBy values(1000,'Bob');
Query OK, 1 row affected (0.18 sec)

mysql> insert into HighestIdOrderBy values(600,'John');
Query OK, 1 row affected (0.16 sec)

mysql> insert into HighestIdOrderBy values(300,'Johnson');
Query OK, 1 row affected (0.18 sec)

mysql> insert into HighestIdOrderBy values(100,'Carol');
Query OK, 1 row affected (0.12 sec)

Display all records from the table with select statement. The query is as follows −

mysql> select *from HighestIdOrderBy;

The following is the output −

+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
|        200 | David        |
|       1000 | Bob          |
|        600 | John         |
|        300 | Johnson      |
|        100 | Carol       |
+------------+--------------+
5 rows in set (0.00 sec)

Here is the query to select maximum id from MySQL table. The query is as follows −

mysql> select *from HighestIdOrderBy order by EmployeeId desc limit 1 offset 0;

The following is the output −

+------------+--------------+
| EmployeeId | EmployeeName |
+------------+--------------+
|       1000 | Bob          |
+------------+--------------+
1 row in set (0.00 sec)
raja
Published on 11-Jan-2019 11:21:54
Advertisements