To select last two rows, use ORDER BY DESC LIMIT 2.
Let us first create a table −
mysql> create table DemoTable763 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FirstName varchar(100) ); Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable763(FirstName) values('John'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable763(FirstName) values('Sam'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable763(FirstName) values('Carol'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable763(FirstName) values('David'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable763(FirstName) values('Bob'); Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable763;
This will produce the following output -
+----+-----------+ | Id | FirstName | +----+-----------+ | 1 | John | | 2 | Sam | | 3 | Carol | | 4 | David | | 5 | Bob | +----+-----------+ 5 rows in set (0.00 sec)
Following is the query to select last two rows in MySQL −
mysql> select *from DemoTable763 order by Id DESC LIMIT 2;
This will produce the following output -
+----+-----------+ | Id | FirstName | +----+-----------+ | 5 | Bob | | 4 | David | +----+-----------+ 2 rows in set (0.00 sec)