There are at least 5 ways to return data from one table which is not in another table. Two of these are SQL Server 2005 and greater only. This is a post mostly for beginners but hopefully everyone will get something out of it.
Here are the 5 different ways
NOT INNOT EXISTSOUTER JOINOUTER APPLY (2005+)EXCEPT (2005+)
Let's see how this all worksFirst create these two tables with the Celko approved naming convention.
CREATE
INSERT
NOT INRun the following Code
SELECT
What happened? Nothing gets returned! The reason is because the subquery returns a NULL and you can't compare a NULL to anything
Now run this
WHERE
This also works
NOT EXISTSNOT EXISTS doesn't have the problem that NOT IN has. Run the following code
FROM
Everything worked
LEFT and RIGHT JOINPlain vanilla LEFT and RIGHT JOINS
LEFT
With a RIGHT Join you just switch the tables around
RIGHT
And we can also do a full outer join
FULL OUTER
AND
You can be real silly and do a subquery LEFT join
SELECT j.* FROM #testjoin j
Now let's talk about SQL 2005 and up
OUTER APPLY (SQL 2005 +)OUTER APPLY is something that got added to SQL 2005
OUTER
(
EXCEPT(SQL 2005 +)EXCEPT is something that got added to SQL 2005. It basically returns everything from the top table which is not in the bottom table
SELECT * FROM #testjoin
EXCEPT
I am also mentioning INTERSECT since some people might not have seen it before. INTERSECT returns what ever is in both tables(like a regular join)
INTERSECT
So there you have it, most likely you already know all these types of joins. If you learned something from this post that is a good thing also.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.