Which way to count a number of rows should be faster in MySQL?
This:
SELECT COUNT(*) FROM ... WHERE ...
Or, the alternative:
SELECT 1 FROM ... WHERE ...
// and then count the results with a built-in function, e.g. in PHP mysql_num_rows()
One would think that the first method should be faster, as this is clearly database territory and the database engine should be faster than anybody else when determining things like this internally.
EXPLAIN SELECT id FROM ....
did the trick for me. and I could see the number of rows underrows
column of the result.After speaking with my team-mates, Ricardo told us that the faster way is:
But you have to remember that the result may not be exact.
You can use it from command line too:
More information: http://dev.mysql.com/doc/refman/5.7/en/show-table-status.html
And you can find a complete discussion at mysqlperformanceblog
If you need to get the count of the entire result set you can take following approach:
This isn't normally faster than using
COUNT
albeit one might think the opposite is the case because it's doing the calculation internally and doesn't send the data back to the user thus the performance improvement is suspected.Doing these two queries is good for pagination for getting totals but not particularly for using
WHERE
clauses.When you
COUNT(*)
it takes in count column indexes, so it will be the best result. Mysql with MyISAM engine actually stores row count, it doensn't count all rows each time you try to count all rows. (based on primary key's column)Using PHP to count rows is not very smart, because you have to send data from mysql to php. Why do it when you can achieve the same on the mysql side?
If the
COUNT(*)
is slow, you should runEXPLAIN
on the query, and check if indexes are really used, and where should they be added.The following is not the fastest way, but there is a case, where
COUNT(*)
doesn't really fit - when you start grouping results, you can run into problem, whereCOUNT
doesn't really count all rows.The solution is
SQL_CALC_FOUND_ROWS
. This is usually used when you are selecting rows but still need to know the total row count (for example, for paging). When you select data rows, just append theSQL_CALC_FOUND_ROWS
keyword after SELECT:After you have selected needed rows, you can get the count with this single query:
FOUND_ROWS()
has to be called immediately after the data selecting query.In conclusion, everything actually comes down to how many entries you have and what is in the WHERE statement. You should really pay attention on how indexes are being used, when there are lots of rows (tens of thousands, millions, and up).
Try this:
I did some benchmarks to compare the execution time of
COUNT(*)
vsCOUNT(id)
(id is the primary key of the table - indexed).Number of trials: 10 * 1000 queries
Results:
COUNT(*)
is faster 7%VIEW GRAPH: benchmarkgraph
My advice is to use:
SELECT COUNT(*) FROM table