MySQL: Get total number of rows when using LIMIT

A SELECT statement may include a LIMIT clause to restrict the number of rows return by the MySQL server. In some cases, it is desirable to know how many rows the SELECT statement would have returned without the LIMIT. To obtain the row count by include SQL_CALC_FOUND_ROWS option in the SELECT statement, and then execute FOUND_ROWS().
[sql]

SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name LIMIT 10;

SELECT FOUND_ROWS();

[/sql]
The second SELECT returns a number indicating how many rows the first SELECT query would have returned without the LIMIT clause. i.e, it returns the total count.

In the absence of the SQL_CALC_FOUND_ROWS option in first SELECT, FOUND_ROWS() returns the number of rows in the result set returned by that statement i.e, it returns only 10.

Permanent link to this article: https://blog.openshell.in/2012/08/mysql-get-total-number-of-rows-when-using-limit/

Leave a Reply

Your email address will not be published.