Select results from the middle of a sorted list in MySQL?


To select results from the middle of a sorted list, use ORDER BY clause along with LIMIT.

Let us first create a table. Following is the query −

mysql> create table sortedListDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(100)
   -> );
Query OK, 0 rows affected (0.46 sec)

Following is the query to insert some records in the table using insert command −

mysql> insert into sortedListDemo(StudentName) values('John');
Query OK, 1 row affected (0.62 sec)

mysql> insert into sortedListDemo(StudentName) values('Sam');
Query OK, 1 row affected (0.18 sec)

mysql> insert into sortedListDemo(StudentName) values('Adam');
Query OK, 1 row affected (0.13 sec)

mysql> insert into sortedListDemo(StudentName) values('James');
Query OK, 1 row affected (0.21 sec)

mysql> insert into sortedListDemo(StudentName) values('Jace');
Query OK, 1 row affected (0.13 sec)

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

mysql> insert into sortedListDemo(StudentName) values('Carol');
Query OK, 1 row affected (0.18 sec)

mysql> insert into sortedListDemo(StudentName) values('Bob');
Query OK, 1 row affected (0.17 sec)

mysql> insert into sortedListDemo(StudentName) values('Ramit');
Query OK, 1 row affected (0.16 sec)

mysql> insert into sortedListDemo(StudentName) values('Chris');
Query OK, 1 row affected (0.21 sec)

mysql> insert into sortedListDemo(StudentName) values('Robert');
Query OK, 1 row affected (0.14 sec)

mysql> insert into sortedListDemo(StudentName) values('David');
Query OK, 1 row affected (0.21 sec)

Following is the query to display all records from the table using select statement −

mysql> select * from sortedListDemo;

This will produce the following output −

+----+-------------+
| Id | StudentName |
+----+-------------+
| 1  | John        |
| 2  | Sam         |
| 3  | Adam        |
| 4  | James       |
| 5  | Jace        |
| 6  | Mike        |
| 7  | Carol       |
| 8  | Bob         |
| 9  | Ramit       |
| 10 | Chris       |
| 11 | Robert      |
| 12 | David       |
+----+-------------+
12 rows in set (0.00 sec)

Following is the query to select results from the middle of a sorted list. We have set LIMIT as 4, 6 that means 6 records will be displayed randomly −

mysql> select *from sortedListDemo
   -> order by StudentName
   -> LIMIT 4,6;

This will produce the following output −

+----+-------------+
| Id | StudentName |
+----+-------------+
| 12 | David       |
| 5  | Jace        |
| 4  | James       |
| 1  | John        |
| 6  | Mike        |
| 9  | Ramit       |
+----+-------------+
6 rows in set (0.00 sec)

Updated on: 30-Jul-2019

805 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements