Limit 1 on unique php mysql queries?

I was curious that one document I read suggests using a limit of 1 for all queries, if available, including indexed and unique columns. Writing constraint 1 really helps queries when using WHERE uniqueCol = val;

+2


source to share


4 answers


No, adding "limit 1" does not speed up your code in these cases. Instead, the usual reason people do it is instead a protective factor. There are two situations where this might help you:

  • Sometimes, depending on the design of your database, you might think that there is only 1 result, but if the column you selected is not a truly unique column, for some strange reason, then you might get two results returned if the integrity of the database not saved. I've seen that in such cases, programmers use the constraint 1 in this case, just to make sure that whatever, they only get one result when they expect only one result, and therefore it doesn't crash the code.

  • And security. I've also seen people preach the idea of ​​putting a limit of 1 in your queries to make it harder for SQL injection. The idea is that if someone manages to do the SQL injection then they only get "1 result". Now the problem with this is that it rarely works in practice, as many SQL injection attacks end up ignoring the "rest of the row" of data.



So in the end? This will certainly not prevent you from putting it there. But there is really no good reason why you should always do this. And in fact, I rarely do it myself, simply because the benefits that you could convince yourself are pretty minimal.

+6


source


Not.



+1


source


No: there is no need to restrict a singleton set to one element.

0


source


In your case, it won't do much good.

You may find this previous discussion of interest Does adding LIMIT 1 queries to MySQL increase faster when you know there will only be one result?

0


source







All Articles