
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
How to 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 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.
- Related Articles
- How to select first and last row record using LIMIT in MySQL?
- How to select first and last data row from a MySQL result?
- How to select last two rows in MySQL?
- How to select next row pagination in MySQL?
- How to select last 10 rows from MySQL?
- Access last inserted row in MySQL?
- Select a random row in MySQL
- MySQL SELECT last few days?
- MySQL LIMIT to select a single row
- Select text after last slash in MySQL?
- How to select row when column must satisfy multiple value in MySQL?
- MySQL query to select one specific row and another random row?\n
- Select last day of current year in MySQL?
- SELECT last entry without using LIMIT in MySQL?
- Select last record and update it in MySQL?

Advertisements