Select last 3 rows from database order by id ASC?

MySQLMySQLi Database

You can use subquery. Following is the syntax −

SELECT * FROM (
   SELECT * FROM yourTableName ORDER BY yourIdColumnName DESC LIMIT 3
) anyAliasName
ORDER BY yourIdColumnName;

Let us first create a table −

mysql> create table DemoTable
(
   ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientName varchar(100)
);
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(ClientName) values('Larry');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(ClientName) values('Chris');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(ClientName) values('Bob');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(ClientName) values('David');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(ClientName) values('Carol');
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(ClientName) values('Robert');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable(ClientName) values('Sam');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(ClientName) values('Mike');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----------+------------+
| ClientId | ClientName |
+----------+------------+
| 1        | Larry      |
| 2        | Chris      |
| 3        | Bob        |
| 4        | David      |
| 5        | Carol      |
| 6        | Robert     |
| 7        | Sam        |
| 8        | Mike       |
+----------+------------+
8 rows in set (0.00 sec)

Following is the query to select last 3 rows from database order by id ASC −

mysql> SELECT * FROM (
   SELECT * FROM DemoTable ORDER BY ClientId DESC LIMIT 3
) tbl
ORDER BY ClientId ASC;

This will produce the following output −

+----------+------------+
| ClientId | ClientName |
+----------+------------+
| 6        | Robert     |
| 7        | Sam        |
| 8        | Mike       |
+----------+------------+
3 rows in set (0.00 sec)
raja
Published on 21-May-2019 07:55:46
Advertisements