best way for select row mysql
سؤال
Which of the following notations is better?
SELECT id,name,data FROM table WHERE id = X
OR
SELECT id,name,data FROM table WHERE id = X LIMIT 1
I think it should not have "LIMIT".
Thanks!
المحلول
If there is a unique constraint on id
then they will be exactly the same.
If there isn't a unique constraint (which I would find highly surprising on a column called id
) then which is better depends on what you want to do:
- If you want to find all rows matching the condition, don't use
LIMIT
. - If you want to find any row matching the condition (and you don't care which), use
LIMIT 1
.
نصائح أخرى
Always use LIMIT with select statement even if you are fetching 1 record because it will speed up your query. So use :
SELECT id,name,data FROM table WHERE id = X LIMIT 1
For example : If there are 1000 records in your table than if you using
SELECT id,name,data FROM table WHERE id = X
than it will traverse through 1000 records even if finds that id But if you using LIMIT like this
SELECT id,name,data FROM table WHERE id = X LIMIT 1
than it will stop executing when finds first record.
لا تنتمي إلى StackOverflow