I have a SQL that looks like this:
SELECT * FROM foo WHERE foo.bar IN (SELECT foobar.bar FROM foobar)
This is not good, right? The nested SELECT will cause things to slow down? How should I query something like this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The IN clause is perfectly valid SQL, but it’s not always the preferred way. I’ve often found that MySQL’s performance on them is pretty poor, even if
foo.baris indexed.If you change it to a join, you have to be careful if the second table has multiple rows that match the join condition for each row of the first table, because the join will produce multiple result rows. If this is possible, the join should be:
The ultimate answer is that you should use EXPLAIN to see how different forms of the query will be executed. But if you’re not experiencing a performance problem in the first place, don’t sweat it.
If you want all the rows where
f.bardoes not exist infoobar,NOT INis usually the most succinct way to write it. But it can also be written using aLEFT OUTER JOIN:You don’t need the subquery in this case because you’re only reporting the non-matching rows, so there obviously can’t be multiple matches in the result.