Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL left outer join on multiple columns

Tags:

sql

join

vertica

According to this SQL join cheat-sheet, a left outer join on one column is the following :

SELECT *
  FROM a
  LEFT JOIN b 
    ON a.foo = b.foo
  WHERE b.foo IS NULL 

I'm wondering what it would look like with a join on multiple columns, should it be an OR or an AND in the WHERE clause ?

SELECT *
  FROM a
  LEFT JOIN b 
    ON  a.foo = b.foo
    AND a.bar = b.bar
    AND a.ter = b.ter
WHERE b.foo IS NULL 
  OR  b.bar IS NULL 
  OR  b.ter IS NULL

or

SELECT *
  FROM a
  LEFT JOIN b 
    ON  a.foo = b.foo
    AND a.bar = b.bar
    AND a.ter = b.ter
WHERE b.foo IS NULL 
  AND b.bar IS NULL 
  AND b.ter IS NULL

?

(I don't think it does, but in case it matters, the db engine is Vertica's)

(I'm betting on the OR one)

like image 839
François M. Avatar asked Oct 13 '16 08:10

François M.


People also ask

Can you join on multiple columns SQL?

If you'd like to get data stored in tables joined by a compound key that's a primary key in one table and a foreign key in another table, simply use a join condition on multiple columns. In one joined table (in our example, enrollment ), we have a primary key built from two columns ( student_id and course_code ).

Can you have multiple left outer JOINs?

Yes, indeed! You can use multiple LEFT JOINs in one query if needed for your analysis.

How do I left join two columns in SQL?

Left Join: SyntaxSELECT * FROM table1 LEFT [ OUTER ] JOIN table2 ON table1. column_name=table2. column_name; SQL LEFT join fetches a complete set of records from table1, with the matching records (depending on the availability) in table2.


2 Answers

That depends on whether the columns are nullable, but assuming they are not, checking any of them will do:

SELECT *
  FROM a
  LEFT JOIN b 
    ON  a.foo = b.foo
    AND a.bar = b.bar
    AND a.ter = b.ter
WHERE b.foo IS NULL -- this could also be bar or ter

This is because after a successful join, all three columns will have a non-null value.

If some of these columns were nullable and you'd like to check if any one of them had a value after the join, then your first (OR) approach would be OK.

like image 116
Cristian Lupascu Avatar answered Sep 21 '22 13:09

Cristian Lupascu


You can use any combination of criteria for joining:

SELECT *
FROM a
LEFT JOIN b ON a.foo = b.foo AND a.bar = b.bar AND a.ter = b.ter

The WHERE clause has nothing to do with the join itself. The WHERE b.foo IS NULL in first query will return all records from a that had no matching records in b or when b.foo was null.

like image 22
Amir Rahimi Farahani Avatar answered Sep 21 '22 13:09

Amir Rahimi Farahani