Quantcast
Channel: ฟอรัม Getting started with SQL Server
Viewing all articles
Browse latest Browse all 8428

Difference between OUTER JOIN and emulated OUTER JOIN using INNER JOINS and UNION ALL

$
0
0

So recently I was playing around with joins on one of my tables and saw that there is a built-in outer join in MS SQL server.  Just for fun I also made 2 statements.  The first one uses an outer join like below:  

SELECT ls1.*, bb.dbo.something.customer_id
FROM bb.some_table ls1
LEFT OUTER JOIN bb.dbo.something ON ls1.retail_customer_pays_ID = bb.dbo.something.customer_id;

The second statement uses a UNION ALL and two INNER JOINS to accomplish exactly the same thing:  


SELECT LS1.*, bb.dbo.something.customer_id
FROM bb.some_table ls1
INNER JOIN bb.dbo.something ON ls1.retail_customer_pays_id = bb.dbo.something.customer_id
 
UNION ALL
 
SELECT ls2.*, CAST(NULL AS VARCHAR(20))
FROM bb.some_table ls2
WHERE NOT EXISTS (
    SELECT * FROM bb.dbo.something
             WHERE ls2.retail_customer_pays_id = bb.dbo.something.customer_id)

When I watch the resources that are used I can see that the second statement is faster by a little bit (note that the tables I am doing this on are not that large so the time difference is not neccessarily something that is correct for alrger tables).  

The part that confuses me is that the second statement that emulates an outer join is accessing more resources so it should take longer.  

So now we come to my actual question:   How does the OUTER JOIN command work on the backend in SQL Server so that it uses less resources?  And why is it slower?  


Viewing all articles
Browse latest Browse all 8428

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>