Quote:
quote:Originally posted by anubhav.kumar
Hi,
Furthur to this, when u use joins,the server creates a execution plan for the query based on indexes defined in the participating tables which enhances performance. If u use the subquery [say as a derived table in From clause] then the result is used as if a table scan is done while running the query.
Also, the example you have sited used correlated query which should be the last option while writing queries, bcse it runs for each record before giving results
Anubhav Kumar
|
Your first comment is simply not true. In fact, the optimizer, for many kinds of subqueries, will generate the exact same execution plan as it would for an inner join. It is also not true that derived tables always result in the creation of a temporary table where a table scan would be necessary. If the optimizer can materialize the derived table from an index it will do so. This is one reason why covering indexes can be so useful.
It's not always easy to know a priori when a subquery would be identical to a join in execution performance, so I agree with the sentiment expressed by other posters that all other things being equal, a JOIN is better than a subquery, if for no other reason than they are easier to read.
However, there are situations where the reverse is true, where a subquery can be "better" than a join and result in better performance (to be sure, there aren't many of these ;).
As well, there are some queries that cannot be expressed by anything other than a correlated subquery, so it can be a necessary tool.
All things being equal, INNER JOINs are preferable to subqueries, but many times not all things are so equal, so one should ALWAYS be wary of advice to always (or never) do anything... ;)
Jeff Mason
Custom Apps, Inc.
[email protected]