How to select the last three rows of a table in ascending order with MySQL?

MySQLMySQLi Database

To select the last three rows in ascending order, use ORDER BY DESC LIMIT as in the below syntax −

select * from
(select * from yourTableName order by yourColumnName desc limit 3) anyAliasName
order by yourColumnName ;

Let us first create a table −

mysql> create table DemoTable1579
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.67 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1579(Name) values('Robert');
Query OK, 1 row affected (0.37 sec)
mysql> insert into DemoTable1579(Name) values('Bob');
Query OK, 1 row affected (0.48 sec)
mysql> insert into DemoTable1579(Name) values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1579(Name) values('Sam');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1579(Name) values('Mike');
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1579;

This will produce the following output −

+----+--------+
| Id | Name   |
+----+--------+
|  1 | Robert |
|  2 | Bob    |
|  3 | Chris  |
|  4 | Sam    |
|  5 | Mike   |
+----+--------+
5 rows in set (0.00 sec)

Following is the query to select the last three rows of a table in ascending order −

mysql> select * from
   -> (select * from DemoTable1579 order by Id desc limit 3) t
   -> order by Id;

This will produce the following output −

+----+-------+
| Id | Name  |
+----+-------+
|  3 | Chris |
|  4 | Sam   |
|  5 | Mike  |
+----+-------+
3 rows in set (0.00 sec)
raja
Published on 16-Dec-2019 10:42:51
Advertisements