Aggregate function COUNT() and mysql_num_rows(), are they same?

from my coding experience, the aggregate function COUNT and mysql_num_rows both return number of rows.

example,



$query = mysql_query("SELECT COUNT(*) as num_rows FROM sample_table");

$row = mysql_fetch_array($query);
$num_of_rows_1 = $row['num_rows'];

$query = mysql_query("SELECT * FROM sample_table");

$num_of_rows_2 = mysql_num_rows($query);


Both $num_of_rows_1 and $num_of_rows_2 return same number.

If COUNT() and mysql_num_rows are the same, which do you think is more efficient, faster?

they may produce the same answer, but they are very different

let’s pretend that you and i are both sitting in new york and i ask you to find out how many people live in los angeles

you can do it two ways – ask everyone in los angeles to fly over to new york, and you count them as they get off the plane(s), or else you go over to los angeles, count them, and then come back with the answer

which do you think is more efficient, faster? :wink:

good analogy. but when should we use COUNT?

use COUNT when you just want the count without seeing any of the individual rows

sorry but i dont get it. any code example?

when you run a SELECT, it returns all the rows that satisfy the query

so, using your example, if you SELECT COUNT(*), you get back one row consisting of one column, with the count as the column value

again using your example, if you SELECT *, you get back as many rows as there are in the table, and each row has all the columns of the table

huge difference

cool, now i get it. hope you could help me fine tune my next problem. i’d posted in PHP folder, it’s about TEXAS HOLDEM game project, i’d figured out my own algo(not with what suggested by member ‘hash’) but i think i have too many round tripsssssssss to DB server for just 2 tables.

if you haven’t read yet, it’s at http://www.sitepoint.com/forums/showthread.php?t=656316

:blush:

sorry, can’t help with that one

nice graphics, though

:slight_smile:

not a problem…but :injured: