• Blogs (9)
    • šŸ“± 236 - 992 - 3846

      šŸ“§ jxjwilliam@gmail.com

    • Version: ā€šŸš€ 1.1.0
  • 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:

    1. select * from table
    2. 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.