To select the last row, we can use ORDER BY clause with desc (descending) property and Limit 1. Let us first create a table and insert some records with the help of insert command.
The query is as follows.
mysql> create table getLastRecord -> ( -> Id int, -> Name varchar(100) -> ); Query OK, 0 rows affected (0.61 sec)
After creating the above table, we will insert records with the help of insert command.
mysql> insert into getLastRecord values(1,'John'); Query OK, 1 row affected (0.13 sec) mysql> insert into getLastRecord values(2,'Ramit'); Query OK, 1 row affected (0.22 sec) mysql> insert into getLastRecord values(3,'Johnson'); Query OK, 1 row affected (0.13 sec) mysql> insert into getLastRecord values(4,'Carol'); Query OK, 1 row affected (0.79 sec)
Display all records with the help of select statement.
mysql> select *from getLastRecord;
The following is the output.
+------+---------+ | Id | Name | +------+---------+ | 1 | John | | 2 | Ramit | | 3 | Johnson | | 4 | Carol | +------+---------+ 4 rows in set (0.00 sec)
Our lats record is with id 4 and Name ‘Carol’. To get the last record, the following is the query.
mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1;
The following is the output.
+------+-------+ | Id | Name | +------+-------+ | 4 | Carol | +------+-------+ 1 row in set (0.00 sec)
The above output shows that we have fetched the last record, with Id 4 and Name Carol.