3

On my script, I have about 15 SQL queries just for counting the number of rows and displaying them to the user.

What is the most efficient way?

Should I use:

$stmt=$cxn->prepare("SELECT id FROM items WHERE seller=?");
$stmt->execute(array($username));
echo $stmt->rowCount();

Or this:

$stmt=$cxn->prepare("SELECT count(*) as count FROM items WHERE seller=?");
$stmt->execute(array($username));   
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
    echo $row['count'];

Thanks in advance.

3
  • 1
    See stackoverflow.com/questions/5315550/… Commented May 20, 2012 at 14:59
  • One more thing, you can group the 15 select count(*)s in to one statement, that might be faster.
    – nycynik
    Commented May 20, 2012 at 15:05
  • Yes sounds good. It would look better too. Thanks
    – alexx0186
    Commented May 20, 2012 at 15:06

3 Answers 3

2

The short answer is Count(*) will be faster.

However, that assumes your not using the data, if you are going to select the data, and you want a count, then use your first method.

("SELECT id FROM items WHERE seller=?");

If you have an index on the table, then that will return almost instantly.

3
  • 1
    Not using the COUNT aggregate means the database will return all the rows, send those over the wire to PHP, which will then report the count. Extremely inefficient use of bandwidth...
    – OMG Ponies
    Commented May 20, 2012 at 15:01
  • Hi Thanks for your response. I see you point, Count seems more viable. Regards
    – alexx0186
    Commented May 20, 2012 at 15:04
  • Yea.. What I mean is, use count, but not if your going to also fetch the data. If you want the data and the count, do the select and then use ->rowCount(). If your not using the data, just use count(1) in the select.
    – nycynik
    Commented May 20, 2012 at 15:04
1

The rowCount command can be used not only for SELECT queries but also for UPDATE,INSERT etc. So that's a benefit for that.

However according to the PDO documentation :

not guaranteed for all databases and should not be relied on for portable applications.

So in your case i'd suggest using count without worrying about preformence, though it will slightly faster.

0

It will be faster to use the MySQL row count. Less bandwidth is needed between PHP and the database.

1
  • Neither rowCount() or $row['count'] communicate with the server. It simply fetches the data from the result set, which is already in memory in PHP. SELECT id returns a much larger result set, which uses a lot more bandwidth, than SELECT COUNT(*), which only returns a single integer value in a single row.
    – Ami
    Commented May 20, 2012 at 15:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.