1

I am counting the entries in my SQL database:

$sql = "SELECT * FROM files WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute([$id]);
$rowCount =$q->rowCount();

The result of $rowCount is 500000. But to output this single number takes 5 seconds! Is it possible to get this result faster?

peace_love
  • 6,229
  • 11
  • 69
  • 157

3 Answers3

2

Use the COUNT() function https://dev.mysql.com/doc/refman/8.0/en/counting-rows.html:

$sql = "SELECT COUNT(*) FROM files WHERE id = ?";

Also ensure that 'id' is an indexed column: https://dev.mysql.com/doc/refman/8.0/en/mysql-indexes.html

d g
  • 1,594
  • 13
  • 13
0
  1. Replace * with a field(use auto-increment id) - This will reduce the time a bit.
  2. Index that field. - If you use indexed field the query performance will increase.
Sankar Subburaj
  • 4,992
  • 12
  • 48
  • 79
0

SELECT * ..., then counting in PHP, requires shoveling all columns of all rows back to PHP. That's a lot of effort for very little gain.

SELECT COUNT(col) ... does the counting in by MySQL, but it must check for whether col is NULL. And it needs to get at the value of col for every row.

SELECT COUNT(*) ... counts the rows by whatever way is most efficient. This involves looking for the 'smallest' index (or the whole table, if no secondary indexes), and counting through it.

You must learn about INDEXes to get anywhere in databases! This is only one minor use for them.

Rick James
  • 135,179
  • 13
  • 127
  • 222