
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Select Last Row in MySQL
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 last 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.
Advertisements