MySQL query to select top n rows efficiently?

MySQLMySQLi Database

Use index to select top n rows efficiently. Let us first create a table −

mysql> create table DemoTable (StudentName varchar(100), StudentScore int );
Query OK, 0 rows affected (0.66 sec)

Example

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John',34);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Carol',55);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Bob',58);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Sam',38);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Mike',48);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Adam',41);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Chris',47);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Robert',40);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('David',89);
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+-------------+--------------+
| StudentName | StudentScore |
+-------------+--------------+
| John        | 34           |
| Carol       | 55           |
| Bob         | 58           |
| Sam         | 38           |
| Mike        | 48           |
| Adam        | 41           |
| Chris       | 47           |
| Robert      | 40           |
| David       | 89           |
+-------------+--------------+
9 rows in set (0.00 sec)

Example

Following is the query to select top n rows efficiently. We have used ORDER BY and skipped 5 rows. After skipping, 3 records are visible, since we have used LIMIT 3 −

mysql> alter table DemoTable ADD INDEX name_score(StudentName,StudentScore);
Query OK, 0 rows affected (0.61 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> select StudentName,StudentScore from DemoTable order by StudentScore LIMIT 5,3;

Output

+-------------+--------------+
| StudentName | StudentScore |
+-------------+--------------+
| Mike        | 48           |
| Carol       | 55           |
| Bob         | 58           |
+-------------+--------------+
3 rows in set (0.00 sec)
raja
Published on 20-Aug-2019 12:48:15
Advertisements