Fetch ordered records after a specific limit in MySQL


For this, you can use a subquery. Let us first create a table −

mysql> create table DemoTable618 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,StudentFirstName varchar(100)
);
Query OK, 0 rows affected (1.45 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable618(StudentFirstName) values('David');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable618(StudentFirstName) values('Chris');
Query OK, 1 row affected (0.44 sec)
mysql> insert into DemoTable618(StudentFirstName) values('Robert');
Query OK, 1 row affected (0.54 sec)
mysql> insert into DemoTable618(StudentFirstName) values('Sam');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable618(StudentFirstName) values('Mike');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable618(StudentFirstName) values('Carol');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable618(StudentFirstName) values('Bob');
Query OK, 1 row affected (3.66 sec)
mysql> insert into DemoTable618(StudentFirstName) values('John');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable618;

This will produce the following output −

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

Here is the query to fetch ordered records after a specific limit −

mysql> select *from (select StudentId,StudentFirstName from DemoTable618 where StudentId >= 5 order by StudentId limit 4) tbl order by tbl.StudentId desc;

This will produce the following output −

+-----------+------------------+
| StudentId | StudentFirstName |
+-----------+------------------+
|         8 | John             |
|         7 | Bob              |
|         6 | Carol            |
|         5 | Mike             |
+-----------+------------------+
4 rows in set (0.00 sec)

Updated on: 23-Aug-2019

63 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements