Forum Moderators: open

Message Too Old, No Replies

count vs mysql num rows

         

bkeep

5:07 am on Feb 24, 2008 (gmt 0)

10+ Year Member



Which is faster/better?
This:

$sql = "SELECT COUNT(*) as NUMBER FROM users WHERE user = '" . $user ."' AND pass = '" . $pass . "'";
$res = mysql_query($sql);
$num = mysql_result($res,0,"NUMBER");

if ($num > 0)
return true;
return false;

or this:


$sql = "SELECT user FROM users WHERE user = '" . $user ."' AND pass = '" . $pass . "'";
$res = mysql_query($sql);
$num = mysql_num_rows($res);

if ($num > 0)
return true;
return false;

I have done a little reading and Have come across that when using the "WHERE" clause using COUNT it can reduce the speed. Is this a significant speed decrease or is it nominal? Also for future ease of changing database venders, would those queries need to be modified to work with PostgreSQL? (in the future I would like to make a database class and allow multiple database types so instead of mysql_query it would be a function called "query" or "fetch" you get the picture.)

Thank You for any information.

Best Regards,
Brandon

physics

9:07 pm on Feb 26, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I would think you're better off using the count(*) version. What matters is the overall speed of the query and in the second case you're calling the mysql_num_rows routine which must have to count the number of rows anyway (not sure if this is faster or slower though). In any case the best way would be to test it out.

Clark

12:03 am on Feb 27, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



test it out
Yes...
Explain [dev.mysql.com] is your friend. It can answer your questions better because sometimes what is theoretically better turns out not to be better for a particular dB.