Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the least expensive method to get a row count for a SQL Query?

Tags:

When writing a query for paging on a web page what is the least expensive method to get a total row count? Is there a way to do this without running a query twice - one for the total and the next for the limit?

Using MySQL

Example: (I want to know if there is a less expensive way)

Get Count

SELECT COUNT(*) FROM table

Get Paging

SELECT mycolumns FROM table LIMIT 100

How can I get the total count without running 2 queries.

like image 257
Todd Moses Avatar asked Feb 26 '10 19:02

Todd Moses


2 Answers

You can run the first query with the SQL_CALC_FOUND_ROWS option, and then run this:

SELECT FOUND_ROWS();

http://dev.mysql.com/doc/refman/5.1/en/information-functions.html#function_found-rows

like image 199
Ike Walker Avatar answered Oct 11 '22 19:10

Ike Walker


This will give you an additional column called Count in each row that contains the total number of rows:

SELECT mycolumns, (select count(*) from table) as Count 
FROM table 
LIMIT 100
like image 25
D'Arcy Rittich Avatar answered Oct 11 '22 17:10

D'Arcy Rittich