Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql speed mysql_num_rows vs query limit 1

Tags:

php

mysql

i had to check if a value (string) is in my database.

at the moment i do a

select a.email,b.vuid from user a, verteiler_user b where a.email=\''.$email.'\' and a.kid=' . $kid.' and b.vid=' . $vid . ' and a.uid = b.uid

as query with a mysql_num_rows, then check if >=1

But is it faster to do a query with limit 1; ? and check if a row is coming back ?

like image 670
Roby Avatar asked Jun 10 '11 05:06

Roby


2 Answers

Yes. It would be faster to run a limit 1 query. And if all you're doing is checking for the existence of a row, why bother returning all those columns? Simply select 1. That will be (negligibly) faster. BTW: Your code looks vulnerable to SQL injection attacks. Consider sanitizing the dynamic parts of your query with mysql_real_escape_string() or a similar function.

like image 52
Asaph Avatar answered Sep 17 '22 17:09

Asaph


LIMIT 1 will have better performance because it will stop matching when the LIMIT has been satisfied.

If you only ever expect 1 row, add LIMIT 1 to your query.

Also, if you are only checking for the presence of that string in the query, there is no need to use column names with SELECT in the query. Just use SELECT 1....

like image 37
alex Avatar answered Sep 19 '22 17:09

alex