- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 order last 5 records by ID in MySQL
You can use subquery for this. Let us first create a table −
mysql> create table DemoTable ( Id int ); Query OK, 0 rows affected (0.68 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(115); Query OK, 1 row affected (0.32 sec) mysql> insert into DemoTable values(200); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable values(140); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(124); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(198); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable values(156); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(178); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(156); Query OK, 1 row affected (0.43 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+ | Id | +------+ | 100 | | 115 | | 200 | | 140 | | 124 | | 198 | | 156 | | 178 | | 156 | +------+ 9 rows in set (0.00 sec)
Here is the query to get last 5 records ordered by ID −
mysql> select *from(select *from DemoTable order by Id DESC limit 5)tbl order by Id;
This will produce the following output −
+------+ | Id | +------+ | 156 | | 156 | | 178 | | 198 | | 200 | +------+ 5 rows in set (0.00 sec)
Advertisements