asotshia
asotshia

Reputation: 121

Which one of those two queries is faster?

Which of the two following queries might be faster?

$cposts = mysql_query("SELECT id FROM posts WHERE company_id = ".$dealid." ");  
$sum_posts= mysql_num_rows($cposts);
echo $sum_posts;

or

$cposts2 = mysql_query("SELECT count(id) as myid FROM posts WHERE company_id = ".$dealid." ");  
$sum_posts2= mysql_fetch_assoc($cposts2);
echo $sum_posts2['myid'];

Upvotes: 0

Views: 75

Answers (2)

voldomazta
voldomazta

Reputation: 1340

I believe the count would be better, and will use less processing.

I would go with this:

$cposts = mysql_query('SELECT COUNT(*) FROM posts WHERE company_id = ' . $dealid);
$num_posts = (int)mysql_result($cposts, 0);
echo $num_posts;

Upvotes: 0

Losbear
Losbear

Reputation: 3314

SELECT COUNT(id)... is MUCH faster. The SQL database will do a count and return just that instead of returning all the records and you doing a count on the application side.

Cheers.

Upvotes: 1

Related Questions