MySQL: 'select count(*)' is much faster than 'select *'
Blogs20112011-06-02
If we want to get the number of table records, normally there are 2 ways to do so:
- select * from table
- select count(*) from table
Examples: (1). use āselect * from tableā
$num_rows=array();
$queries = array('select * from a', 'select * from b', ...);
foreach ($queries as $sql) {
$result = mysql_query($sql, $link);
$num_rows[] = mysql_num_rows($result);
mysql_free_result($result);
}
// use $num_rows[0], $num_rows[1] to get the table number.(2). use āselect count(*) from tableā
$num_rows=array();
$queries = array('select count(*) from a', 'select count(*) from b', ..);
foreach ($queries as $sql) {
$result = mysql_query($sql, $link);
$num_rows[] = mysql_fetch_row($result);
mysql_free_result($result);
}
// $num_rows[0][0],$num_rows[1][0] instead of $num_rows[0], $num_rows[1]...The above 2 are not the same, with very big difference. I found āselect count(*) from tableā (2) is much faster than āselect * from tableā (1). For total 4 tables, which records from 1000 to 260000, the speed is 2.78S vs. 32ms. The (2) is 9 times quicker than (1).
The (1) fetch all records and use mysql_num_rows to sum up the total number, eats a lot of memory. The (2) just get the total number of the table, no table data touched, so save huge memory. And, (1) is to search table itself; while (2) is to search table index, so 2 is much quicker.
So, for a indexed table, it is a better choice to always use (2) āselect count(*) from tableā to get the table number.
