Getting the last 30 rows in MySQL


To get the last 30 rows in MySQL, you need to use ORDER BY DESC and then LIMIT 30. The syntax is as follows −

select * from yourTableName order by yourColumnName DESC LIMIT 30;

Let us first create a table −

mysql> create table DemoTable1567
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY
   -> );
Query OK, 0 rows affected (0.82 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1567 values(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),(),();
Query OK, 37 rows affected (0.37 sec)
Records: 37  Duplicates: 0  Warnings: 0

Display all records from the table using select statement −

mysql> select * from DemoTable1567;

This will produce the following output −

+----+
| Id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |
|  9 |
| 10 |
| 11 |
| 12 |
| 13 |
| 14 |
| 15 |
| 16 |
| 17 |
| 18 |
| 19 |
| 20 |
| 21 |
| 22 |
| 23 |
| 24 |
| 25 |
| 26 |
| 27 |
| 28 |
| 29 |
| 30 |
| 31 |
| 32 |
| 33 |
| 34 |
| 35 |
| 36 |
| 37 |
+----+
37 rows in set (0.00 sec)

Following is the query to get last 30 rows −

mysql> select * from DemoTable1567 order by Id DESC LIMIT 30;

This will produce the following output −

+----+
| Id |
+----+
| 37 |
| 36 |
| 35 |
| 34 |
| 33 |
| 32 |
| 31 |
| 30 |
| 29 |
| 28 |
| 27 |
| 26 |
| 25 |
| 24 |
| 23 |
| 22 |
| 21 |
| 20 |
| 19 |
| 18 |
| 17 |
| 16 |
| 15 |
| 14 |
| 13 |
| 12 |
| 11 |
| 10 |
|  9 |
|  8 |
+----+
30 rows in set (0.00 sec)

Updated on: 13-Dec-2019

408 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements