Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL count rows performance

For an InnoDB storage is it better to count the total number of records by

  • Using mysql_num_rows on

    select * from tbl where pk = 1
    

or by

  • fetching the array and retrieve the "total" value from

    select count(*) as total from tbl where pk = 1
    

?

like image 279
Wolfgang Avatar asked Dec 06 '09 12:12

Wolfgang


People also ask

Which is faster count (*) or count 1?

The simple answer is no – there is no difference at all. The COUNT(*) function counts the total rows in the table, including the NULL values. The semantics for COUNT(1) differ slightly; we'll discuss them later. However, the results for COUNT(*) and COUNT(1) are identical.

Is MySQL count fast?

The MyISAM engine maintains a count of all rows in a table, making counts in MySQL/MyISAM spectacularly fast. However, if you've done counts with InnoDB, another popular MySQL storage engine, or with a PostgreSQL table, then you know a count query takes much longer.

Are count queries faster?

Less data needs to be transferred and processed.Your COUNT query will only ever result in one row with one value so this will be quick, the other query could result in a great many rows being transferred to, and processed by, the application.

How do I count rows in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.


3 Answers

Absolutely the latter. It can grab the value direct from the PK's index, whereas the former almost certainly requires a table scan (unless every single column is part of an index; and even then, it has to grab values from all over the indexes). Then depending on how you're connecting to the DB, there's a large amount of data transit just to get a count.

explain can help here. In this case, it'll tell you that the select is optimized away.

like image 89
T.J. Crowder Avatar answered Oct 09 '22 14:10

T.J. Crowder


In addition to Zxpro's answer, there is also the MySQL internal effort:

select * from tbl where pk = 1

forces MySQL to retrieve matching rows physically; whereas

select count(*) as total from tbl where pk = 1 

allows MySQL to count entries in the primary key, without retrieving any table rows

like image 32
Steve De Caux Avatar answered Oct 09 '22 16:10

Steve De Caux


The latter is most likely to perform better since your are only transmitting a single integer whereas, in the first scenario, you'll be sending a whole lot more data.

like image 43
Bryan Menard Avatar answered Oct 09 '22 15:10

Bryan Menard