I have two tables with a field that the two may have in common. I want the records from one table where that field does not exist in the other table. It works well except that it returns some records that are in fact in the other table. I have checked for NULLs, leading and trailing spaces, and can find no reason why this is happening. When I find a record that should not be returned but is I can query the other tables for that record and both will return the matching record.
FauxTable1:
SKU | Description | Cost
123 | Pink Bike | 20
456 | Blue Bike |25
ABC | Drumset | 50
DEF | Horn | 35
FauxTable2
SKU | Description | Cost
123 | Pink Bike | 20
456 | Blue Bike |25
GHI | Snake Skin | 15
JKL | Pajamas | 7
SELECT *
From FauxTable1
whereSKU NOT IN (Select SKU from FauxTable2 )
Expected Result:
SKU | Description | Cost
ABC | Drumset | 50
DEF | Horn | 35
Example Messed up Result:
SKU | Description | Cost
456 | Blue Bike |25
ABC | Drumset | 50
DEF | Horn | 35
I have simplified the number of columns etc for the example. I am trying to figure out what may cause this query to return results that are IN both tables along with results that are NOT IN but it doesn't return all results that are IN
1) NOT IN
2) NOT EXISTS
3) LEFT JOIN + IS NULL
The choice can depend on the cardinality of your tables, and how they indexed. Based on your simplified example, I might use the third option, since it does not require a subquery, as follows:
SELECT t1.*
FROM FauxTable1 t1 LEFT JOIN FauxTable2 t2 ON t1.sku = t2.sku
WHERE t2.sku IS NULL