I need to build a query that will show me records that are in Table 1, but that are not in Table 2, based on the make-model-serial number combination.
I know for fact that there are 4 records that differ, but my query always comes back blank.
SELECT *
FROM Table1 WHERE MAKE+MODEL+[Serial Number] NOT IN
(SELECT make+model+[serial number] FROM Table2)
Table 1 has 5 records.
When I change the query to IN
, I get 1 record. What am I doing wrong with the NOT
?
One issue could be that if either make, model, or [serial number] were null, values would never get returned. Because string concatenations with null values always result in null, and not in () with null will always return nothing. The remedy for this is to use an operator such as IsNull(make, '') + IsNull(Model, ''), etc.
It's because of the way NOT IN works.
To avoid these headaches (and for a faster query in many cases), I always prefer NOT EXISTS:
That worked for me, where
make+model+[serial number]
was one field nameUse a LEFT JOIN checking the right side for nulls.
The above would match up TableA and TableB based on the Id column in each, and then give you the rows where the B side is empty.
You're probably better off comparing the fields individually, rather than concatenating the strings.