MySQL pagination without double-querying?


To work with MySQL pagination, firstly let us see how to use CREATE command and use it to create a table.

mysql>CREATE table RowCountDemo
   -> (
   -> ID int,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.95 sec)

Records are inserted with the help of INSERT command.

mysql>INSERT into RowCountDemo values(1,'Larry');
Query OK, 1 row affected (0.15 sec)

mysql>INSERT into RowCountDemo values(2,'John');
Query OK, 1 row affected (0.13 sec)

mysql>INSERT into RowCountDemo values(3,'Bela');
Query OK, 1 row affected (0.15 sec)

mysql>INSERT into RowCountDemo values(4,'Jack');
Query OK, 1 row affected (0.11 sec)

mysql>INSERT into RowCountDemo values(5,'Eric');
Query OK, 1 row affected (0.19 sec)

mysql>INSERT into RowCountDemo values(6,'Rami');
Query OK, 1 row affected (0.49 sec)

mysql>INSERT into RowCountDemo values(7,'Sam');
Query OK, 1 row affected (0.14 sec)

mysql>INSERT into RowCountDemo values(8,'Maike');
Query OK, 1 row affected (0.77 sec)

mysql>INSERT into RowCountDemo values(9,'Rocio');
Query OK, 1 row affected (0.13 sec)

mysql>INSERT into RowCountDemo values(10,'Gavin');
Query OK, 1 row affected (0.19 sec)

Display all the records with the help of SELECT statement.

mysql>SELECT* from RowCountDemo;

The following is the output.

+------+-------+
| ID   | Name  |
+------+-------+
|    1 | Larry |
|    2 | John  |
|    3 | Bela  |
|    4 | Jack  |
|    5 | Eric  |
|    6 | Rami  |
|    7 | Sam   |
|    8 | Maike |
|    9 | Rocio |
|   10 | Gavin |
+------+-------+
10 rows in set (0.00 sec)

Let us now see the syntax for pagination without double querying.

SELECT column_name From  `yourTableName` WHERE someCondition LIMIT value1, value2;

Applying the above syntax now.

mysql> SELECT ID,Name FROM `RowCountDemo` WHERE ID > 0 LIMIT 0, 11;

Here is the output of the above query.

+------+-------+
| ID   | Name  |
+------+-------+
|    1 | Larry |
|    2 | John  |
|    3 | Bela  |
|    4 | Jack  |
|    5 | Eric  |
|    6 | Rami  |
|    7 | Sam   |
|    8 | Maike |
|    9 | Rocio |
|   10 | Gavin |
+------+-------+
10 rows in set (0.00 sec)

Updated on: 30-Jul-2019

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements