Get total number of rows while using LIMIT in MySQL?

MySQLMySQLi Database

To get the total number of rows when using LIMIT, use the following syntax −

select SQL_CALC_FOUND_ROWS * FROM yourTableName LIMIT 0,yourLastValue;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table RowsUsingLimit
   -> (
   -> Id int NOT NULL, 
   -> Name varchar(10)
   -> );
Query OK, 0 rows affected (3.50 sec)

Now you can insert some records in the table using insert command. The query is as follows −

mysql> insert into RowsUsingLimit values(10,'Larry');
Query OK, 1 row affected (0.17 sec)
mysql> insert into RowsUsingLimit values(9,'Mike');
Query OK, 1 row affected (0.19 sec)
mysql> insert into RowsUsingLimit values(15,'Sam');
Query OK, 1 row affected (0.18 sec)
mysql> insert into RowsUsingLimit values(20,'Bob');
Query OK, 1 row affected (0.17 sec)
mysql> insert into RowsUsingLimit values(1,'Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into RowsUsingLimit values(18,'David');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using a select statement. The query is as follows −

mysql> select *from RowsUsingLimit;

The following is the output −

+----+-------+
| Id | Name  |
+----+-------+
| 10 | Larry |
|  9 | Mike  |
| 15 | Sam   |
| 20 | Bob   |
|  1 | Carol |
| 18 | David |
+----+-------+
6 rows in set (0.00 sec)

Here is the query to get the total number of rows while using limit −

mysql> select SQL_CALC_FOUND_ROWS * FROM RowsUsingLimit LIMIT 0,6;

The following is the output −

+----+-------+
| Id | Name  |
+----+-------+
| 10 | Larry |
|  9 | Mike  |
| 15 | Sam   |
| 20 | Bob   |
|  1 | Carol |
| 18 | David |
+----+-------+
6 rows in set (0.00 sec)
raja
Published on 27-Feb-2019 08:22:33
Advertisements