
- 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 two rows in MySQL?
To select last two rows, use ORDER BY DESC LIMIT 2.
Let us first create a table −
mysql> create table DemoTable763 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100) ); Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable763(FirstName) values('John'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable763(FirstName) values('Sam'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable763(FirstName) values('Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable763(FirstName) values('David'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable763(FirstName) values('Bob'); Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable763;
This will produce the following output -
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | John | | 2 | Sam | | 3 | Carol | | 4 | David | | 5 | Bob | +----+-----------+ 5 rows in set (0.00 sec)
Following is the query to select last two rows in MySQL −
mysql> select *from DemoTable763 order by Id DESC LIMIT 2;
This will produce the following output -
+----+-----------+ | Id | FirstName | +----+-----------+ | 5 | Bob | | 4 | David | +----+-----------+ 2 rows in set (0.00 sec)
- Related Articles
- How to select last 10 rows from MySQL?
- How to select all rows from a table except the last one in MySQL?
- How to select last row in MySQL?
- How to select the last three rows of a table in ascending order with MySQL?
- Select two random rows in a MySQL database?
- How select specific rows in MySQL?
- Select only 5 random rows in the last 50 entries With MySQL?
- How to select rows with condition via concatenate in MySQL?
- How to select MySQL rows in the order of IN clause?
- MySQL SELECT last few days?
- MySQL query to select too many rows?
- MySQL query to select multiple rows effectively?
- Getting the last 30 rows in MySQL
- Select text after last slash in MySQL?
- Select all duplicate MySQL rows based on one or two columns?

Advertisements