Do I need to write LIMIT 1 using PDO's fetch() method? This assumes that I need only one result. I'm wondering, does using LIMIT 1 will help to save resources and loading time?
- 151,519
- 37
- 317
- 271
- 62,714
- 68
- 259
- 405
-
Are you by chance downvoting every answer you receive? :-P – Álvaro González Jun 29 '11 at 17:22
-
strictly speaking, PDO::fetch() can be used with multiple rows as well, using the while loop. and in this case adding limit 1 will be counter-productive – Your Common Sense Apr 08 '22 at 07:56
2 Answers
The LIMIT clause is just one more SQL feature you can use to retrieve the information you need. Asking whether you need LIMIT cannot be answered unless you narrow your context. It's like asking if you need WHERE or JOIN. It depends on your data and your needs.
Not sure if that's what you have in mind, but I've seen projects where the developer was not fluent in SQL and just did the heavy lifting in application code, typically restricting their SQL to SELECT * FROM table. I think it's worthwhile to learn the basics of SQL so you're able to return the exact rows and columns you need. That's often a great boost for performance.
- 135,557
- 38
- 250
- 339
Limit is applied after the query is run, so it won't really reduce the resources used by the database server. However it will reduce the amount of resources used by PHP to store the result.
- 1,247
- 10
- 22
-
Doesn't make sense. `Limit is applied after the query is run`? Why would LIMIT be applied only after the query is run? – Gajus Jun 29 '11 at 11:23
-
It isn't true, the database can be more effective if you're using limit. – joakimdahlstrom Jun 29 '11 at 11:31
-
It can be more efficient; however if you try `EXPLAIN SELECT * FROM `sometable` WHERE 1 LIMIT 1` you'll see that it selects all the rows – ianbarker Jun 29 '11 at 13:12