Get Last Entry in a MySQL table?

MySQLMySQLi Database

You can get the last entry in a MySQL table using ORDER BY. The first approach is as follows:

Case 1: Using DESC LIMIT

SELECT * FROM yourTableName ORDER BY yourColumnName DESC LIMIT 1;

The second approach is as follows:

Case 2: Using MAX()

SET @anyVariableName = (SELECT MAX(yourColumnName) FROM yourTableName);
SELECT *FROM yourtableName WHERE yourColumnName = @anyVariableName;

Now to understand both the approaches, let us create a table. The query to create a table is as follows:

mysql> create table lastEntryDemo
   -> (
   -> Id int NOt NULL AUTO_INCREMENT,
   -> Name varchar(30),
   -> Age int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.71 sec)

Insert some records in the table using insert command. The query is as follows:

mysql> insert into lastEntryDemo(Name,Age) values('Larry',24);
Query OK, 1 row affected (0.14 sec)

mysql> insert into lastEntryDemo(Name,Age) values('John',21);
Query OK, 1 row affected (0.19 sec)

mysql> insert into lastEntryDemo(Name,Age) values('David',22);
Query OK, 1 row affected (0.18 sec)

mysql> insert into lastEntryDemo(Name,Age) values('Bob',25);
Query OK, 1 row affected (0.20 sec)

mysql> insert into lastEntryDemo(Name,Age) values('Carol',29);
Query OK, 1 row affected (0.17 sec)

mysql> insert into lastEntryDemo(Name,Age) values('Mike',23);
Query OK, 1 row affected (0.14 sec)

mysql> insert into lastEntryDemo(Name,Age) values('Sam',20);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement. The query is as follows:

mysql> select *from lastEntryDemo;

The following is the output:

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  1 | Larry |   24 |
|  2 | John  |   21 |
|  3 | David |   22 |
|  4 | Bob   |   25 |
|  5 | Carol |   29 |
|  6 | Mike  |   23 |
|  7 | Sam   |   20 |
+----+-------+------+
7 rows in set (0.00 sec)

Here is the query to get last entry using ORDER BY.

Case 1: DESC LIMIT

The query is as follows:

mysql> select *from lastEntryDemo order by Name desc limit 1;

The following is the output:

+----+------+------+
| Id | Name | Age  |
+----+------+------+
| 7  | Sam  | 20   |
+----+------+------+
1 row in set (0.00 sec)

Case 2: Using MAX()

The query is as follows:

mysql> set @MaxId = (select max(Id) from lastEntryDemo);
Query OK, 0 rows affected (0.00 sec)

mysql> select *from lastEntryDemo where Id = @MaxId;

The following is the output:

+----+------+------+
| Id | Name | Age  |
+----+------+------+
| 7  | Sam  | 20   |
+----+------+------+
1 row in set (0.00 sec)
raja
Published on 01-Feb-2019 11:52:24
Advertisements