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
?
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.
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.
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.
MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With