Search code examples
sqlsql-serverjoinleft-joinsql-server-2017

Left-join EXCLUDING matching records?


Traditional left-join returns all records from the left table, including matching records:

enter image description here

I want to use the join to exclude matching records, and return only non-matching records from the left table:

enter image description here

Shown below, is the code I came up with so far.
It uses a WHERE clause to weed out matching records - but this feels wrong somehow.
Is this the best way to do this? Or is there a better method of exclusive joining?

SELECT L.col1 ,
       L.col2 ,
FROM leftTable L
LEFT JOIN rightTable R ON R.col1 = L.col1
WHERE R.id IS NULL ;

Solution

  • The LEFT JOIN method is fine. It is optimized in many databases. Personally, I prefer NOT EXISTS, because I think it is more concise:

    SELECT L.col1, L.col2
    FROM leftTable L
    WHERE NOT EXISTS (SELECT 1 FROM rightTable R WHERE R.col1 = L.col1);
    

    That is, the logic is in one place (the NOT EXISTS expression) rather than being spread over two query clauses.