Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ;
like image 487
Giffyguy Avatar asked Jan 26 '26 08:01

Giffyguy


2 Answers

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.

like image 145
Gordon Linoff Avatar answered Jan 28 '26 23:01

Gordon Linoff


Use Except to interpret

   Select * from table t LEFT JOIN 
     TABLE1 t1
   On t.id=t1.id
   Except
 SELECT * FROM TABLE1
like image 22
Himanshu Avatar answered Jan 28 '26 22:01

Himanshu