Difference between subquery and join
When comparing subqueries and joins, which one is faster?
The best answer is: it depends. It depends on which database system you're using. It depends on how sophisticated the optimizer is. It depends on which indexes you have defined on the columns. It depends on how complex the query is. It depends on whether the current month name has an R in it. Okay, I was kidding about that last one.
Here are two interesting articles that touch this issue in slightly more detail than I would:
- How to Misuse SQL's FROM Clause
by Stéphane Faroult - Dr. Tom's Workshop: Multiple-Child Aggregation
by Tom Moreau
The final answer? You will have to run performance tests on your own tables with your own subqueries and joins, and compare the results. That was my advice in NOT EXISTS correlated subquery, or OUTER JOIN? (20 September 2004).
That said, my preference is often for the subquery. A subquery just seems to convey the semantics of what the query is trying to achieve better than a join. For an example, see my previous answer Subquery or join? (20 October 2003).