How to limit records to only the last five results in MySQL


To fetch only the last five records below is the syntax −

select *from yourTableName order by yourColumnName DESC LIMIT 5;

Let us first create a table −

mysql> create table DemoTable820(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   CustomerName varchar(100)
);
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable820(CustomerName) values('Chris');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable820(CustomerName) values('Robert');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable820(CustomerName) values('David');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable820(CustomerName) values('Bob');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable820(CustomerName) values('Carol');
Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable820(CustomerName) values('Adam');
Query OK, 1 row affected (0.08 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable820;

This will produce the following output −

+----+--------------+
| Id | CustomerName |
+----+--------------+
|  1 | Chris        |
|  2 | Robert       |
|  3 | David        |
|  4 | Bob          |
|  5 | Carol        |
|  6 | Adam         |
+----+--------------+
6 rows in set (0.00 sec)

Following is the query to limit records to only the last five results −

mysql> select *from DemoTable820 order by Id DESC LIMIT 5;

This will produce the following output −

+----+--------------+
| Id | CustomerName |
+----+--------------+
|  6 | Adam         |
|  5 | Carol        |
|  4 | Bob          |
|  3 | David        |
|  2 | Robert       |
+----+--------------+
5 rows in set (0.00 sec)

Updated on: 03-Sep-2019

237 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements