If your only goal is to check if a row exists in php (true or false), what is the best way to do it?
Option 1?
$result = mysql_query("SELECT * FROM users WHERE id = '1'");
$num_rows = mysql_num_rows($result);
if ($num_rows == 1)
// one user, like it should be.
else
// do something else
Option 2?
$query = mysql_query("select count(1) from users where id = 1")
if (mysql_result($query, 0) == 1)
// one user, like it should be.
else
// do something else
Option 3?
$query = mysql_query("something like SELECT EXISTS( SELECT */1/COUNT(*)/etc. ...)")
if (mysql_result($query, 0) == 1)
// one user, like it should be.
else
// do something else
Beter option 4?
you name it.
Subquestions
COUNT(*), COUNT(1) or COUNT(id)
?
Option 3 is the fastest way to check if a row exists if you are using MySQL:
The
EXISTS
is faster thenSELECT COUNT(*)
because the subquery will stop searching when it finds one row. It won't have to find them all and count them. It will return either 0 or 1:I think the question refers more the code itself then the time involved, so using his query: