Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redshift left outer join is leaving out nulls

As background, I've set up 100's of redshift query's, many much more complex than this and yet I think I must be missing something simple.

I am doing a left outer join between Table 1 and Table 2. The tables are essentially this:

Table1
Col1  Col2 Col3
A     C    E
A     D    F

Table2
Col 1 Col2 Col3
A     C    Z

I have no where statements. My on statement is:

on Table1.Col1 = Table2.Col1 and Table1.Col2 = Table2.Col2

My result table is:

ResultTable:
Col1 Col2 Col3 Col4
A    C    E    Z

I was expecting:

ExpectedTable:
Col1 Col2 Col3 Col4
A    C    E    Z
A    D    F    Null

What am I missing? Thanks.

like image 629
Elm Avatar asked Jan 22 '15 03:01

Elm


People also ask

Why does LEFT join return NULL?

The LEFT JOIN command returns all rows from the left table, and the matching rows from the right table. The result is NULL from the right side, if there is no match.

Does LEFT join include NULLs?

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.

Does Redshift join NULLs?

This may not be your problem, but Redshift doesn't match records using the equality operator if any of the columns used in the join are null, even if the column value is null on both sides of the join. To handle this add an or condition for each join checking if both sides are null.

Does LEFT join return NULL rows?

Left Join returns a null even when the match exists.


1 Answers

This may not be your problem, but Redshift doesn't match records using the equality operator if any of the columns used in the join are null, even if the column value is null on both sides of the join.

To handle this add an or condition for each join checking if both sides are null.

e.g. ((a.col1 = b.col1) or (a.col1 is null and b.col1 is null))

like image 189
Dan Avatar answered Sep 30 '22 07:09

Dan