
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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)
- Related Questions & Answers
- How to order records and fetch some using MySQL LIMIT?
- Limit length of longtext field in MySQL SELECT results?
- Limit total number of results across tables in MySQL?
- Find last five digits of a given five digit number raised to power five in C++
- How to limit the number of results returned from grep in Linux?
- How to order last 5 records by ID in MySQL
- How to select first and last row record using LIMIT in MySQL?
- MongoDB Aggregate to limit the number of records
- MySQL query to return 5 random records from last 20 records?
- How to merge MySQL results?
- SELECT last entry without using LIMIT in MySQL?
- How to get the last N records in MongoDB?
- Pull MySQL records for the last 60 minutes?
- MySQL regexp to display only records with strings or strings mixed with numbers. Ignore only the number records
- Create a Stored Procedure with MySQL and set a limit to display only a specific number of records
Advertisements