One way to find the rows from one table that don't match another table is to use a sub-query. Here is an example:
--create and populate tablescreate table table1(col1 int null)create table table2(col1 int null)
insert into table1(col1)select 1UNION select 2UNION select 3
insert into table2(col1)select 1UNION select 3
--Run this query to find out that the value 2 is missing from table2select col1 from table1where col1 not in(select col1 from table2)
NULLs are allowed in the col1 column of table2. If there is aNULL row, you will get invalid results.
--Insert NULLinsert into table2(col1)select NULL
--This returns no results, even though the value 2 is still missingselect col1 from table1where col1 not in(select col1 from table2)
In my opinion, this is a bit tricky to understand. Recall that anything compared to NULL returns unknown. When the value 2 from table1 is compared to the NULL in table2, unknown is returned. That means that it is impossible to know if 2 has a match in table2.
One way around this is to make sure that no NULL values are in the sub-query:
select col1 from table1where col1 not in(select col1 from table2 where col1 is not null)
My favorite way to write this query is to use a left join:
select t1.col1from table1 t1 left join table2 t2on t1.col1 = t2.col1where t2.col1 is null
Find all rows in table1 even if there isn't a match in table2. Then filter to return only the rows that don't match.
--********************************Learn more T-SQL tips by attending the End to End T-SQL course http://www.endtoendtraining.com/public/classes/coursedetails.aspx?courseid=17 to be held in Orlando March 21 and April 1. This course is geared for T-SQL beginners.
http://www.sqlservercentral.com/NewsletterArchive/2008/01/23/384787
After a couple of months of discussion, End to End Training has scheduled me to teach a two day beginning T-SQL course for them. One of the best aspects of End to End Training is that the courseware is written by the trainers. It’s a lot more work to come up with the materials than to use Microsoft’s or some other packaged course, but the course ends up being a better value because it is based on the trainer’s real world experience. My goals for this course are to get the students to be proficient in the basics and to give them the tools needed to solve more complex problems. It will be very hands-on and lots of fun for the students. The price is right, too, only $299. So, if you are new to T-SQL or your company has developers who need to learn T-SQL, be sure to check it out: http://www.endtoendtraining.com/tsql.aspx .