Use A Union Or A Join - What Is Faster [closed]
开发者_如何学Python
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this questionI just wonder if you had a table and you unioned it would it be more efficent then using a join??
I do know that the join creates more columns but this is more theoretical - Will the union need to do a nested loop scan of the other table like a join would have to?
Union will be faster, as it simply passes the first SELECT statement, and then parses the second SELECT statement and adds the results to the end of the output table.
The Join will go through each row of both tables, finding matches in the other table therefore needing a lot more processing due to searching for matching rows for each and every row.
EDIT
By Union, I mean Union All as it seemed adequate for what you were trying to achieve. Although a normal Union is generally faster then Join.
EDIT 2 (Reply to @seebiscuit 's comment)
I don't agree with him. Technically speaking no matter how good your join is, a "JOIN" is still more expensive than a pure concatenation. I made a blog post to prove it at my blog codePERF[dot]net. Practically speaking they serve 2 completely different purposes and it is more important to ensure your indexing is right and using the right tool for the job.
Technically, I think it can be summed using the following 2 execution plans taken from my blog post:
UNION ALL
Execution Plan
JOIN
Execution Plan
Practical Results
Practically speaking the difference on a clustered index lookup is negligible:
JOIN
and UNION
have two different purposes. JOIN
is used to add additional tables to a query for the purpose of adding selection criteria and possibly additional columns. UNION
is used to combine the results of two distinct queries with the same columns. Asking which is more efficient is like asking which of "a loaf of bread" and "the blowing wind" is more "orange".
sorry to break your party, but a well written join will be faster than a union.
- it uses more lightweight statistics collection model (based on cardinality, rather than random dives)
- query will get parsed only once (no need for multiple subselect evaluation)
- resultset will not be materialized in a temptable (it gets even for UNION ALL)
A single SELECT will use no more than one index per table. A UNION will use no more than one index per SELECT in the union.
The UNION will make better use of indexes which could result in a faster query.
精彩评论