Snowflake SQL Tutorial 25 - LEFT and RIGHT OUTER JOIN in Snowflake

Snowflake SQL · Episode 25

In this post we are going to cover the LEFT and RIGHT OUTER JOIN in Snowflake.

An inner join keeps only the rows that found a match, which is why it threw two rows away last post. An outer join is how we keep them. We pick a side, Snowflake promises to return every row on that side, and the columns that had nothing to match come back as NULL.

We will start with the left join and work out where those NULLs actually come from, because every trap further down the page is a consequence of it. Then the right join, then the query those NULLs make possible. At the end we will look at two traps that quietly undo an outer join without raising a single error.

Every query below was run on a real Snowflake account, and every result you see is the output it gave back.

Episode 25 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.

Let's pick up where the last post left off

This page uses the same two tables as episode 24. EMPLOYEES has 8 rows and DEPARTMENTS has 4. Both tables are shown in full at the top of the inner join post, so have a look at them again there if you want to before reading on.

Two rows carry the whole post, exactly as they did last time.

  • Grace has DEPT_ID set to NULL, so she matches no department.
  • Operations, department 40, has no employees at all.

An inner join dropped both of them. An outer join is how we keep them, and there are three flavours of it. Here is the whole ladder, so you can see where this post sits.

JoinWhich rows it keepsRows returnedCovered in
INNER JOINOnly rows that match on both sides7Episode 24
LEFT JOINEvery row on the left, matched or not8this episode
RIGHT JOINEvery row on the right, matched or not8this episode
FULL JOINEvery row on both sides9Episode 26

Have a look at the two eights. They are not the same eight rows, and the middle of this page is about why that matters more than it sounds like it should.

Let's start with a LEFT JOIN

Let's take the inner join from last post and change one word. Everything else stays exactly as it was: the select list, the ON clause and the ordering.

Query
SELECT E.FIRST_NAME, E.DEPT_ID, D.DEPT_NAME, D.LOCATION
FROM EMPLOYEES E
LEFT JOIN DEPARTMENTS D ON E.DEPT_ID = D.DEPT_ID
ORDER BY E.EMP_ID;
Result8 rows · 4 columns
FIRST_NAMEDEPT_IDDEPT_NAMELOCATION
Aisha10EngineeringCharlotte
Marcus10EngineeringCharlotte
Lena20FinanceCharlotte
Tomas20FinanceCharlotte
Priya30MarketingRaleigh
Daniel10EngineeringCharlotte
Sofia30MarketingRaleigh
GraceNULLNULLNULL

Every employee is in the result, Grace included. A LEFT JOIN keeps every row of the table on the left of the keyword, whether or not it found a partner on the right.

Where the NULLs come from

Look at Grace's row. Her DEPT_ID is NULL, which it always was. That value is stored in EMPLOYEES. But DEPT_NAME and LOCATION are NULL too, and those two did not come from any table.

The reasoning is worth following slowly, because every trap further down this page is a consequence of it. The query asks for D.DEPT_NAME and D.LOCATION. For Grace there is no matching DEPARTMENTS row to take them from. The join has promised to return her anyway. So Snowflake manufactures a department row made entirely of NULLs and joins her to that.

Invented, not stored

Go back to the DEPARTMENTS grid in Episode 24 and look for a row of NULLs. There isn't one. Every department in that table has an ID, a name and a location.
The NULLs in Grace's row were invented by the join, not read out of the data. That one sentence explains the COUNT(*) trap and the WHERE trap at the bottom of this page.

Now let's write OUTER out in full

LEFT JOIN and LEFT OUTER JOIN are the same thing, in the same way that JOIN and INNER JOIN were the same thing last post. Let's write the keyword out and see.

Query — OUTER written out in full
SELECT E.FIRST_NAME, D.DEPT_NAME
FROM EMPLOYEES E
LEFT OUTER JOIN DEPARTMENTS D ON E.DEPT_ID = D.DEPT_ID
ORDER BY E.EMP_ID;
Result8 rows · 2 columns
FIRST_NAMEDEPT_NAME
AishaEngineering
MarcusEngineering
LenaFinance
TomasFinance
PriyaMarketing
DanielEngineering
SofiaMarketing
GraceNULL

The same eight employees, with Grace still carrying a NULL department name. This query selects two columns instead of four, so the grid is narrower than the one above it. Spelling out OUTER changed nothing except the length of the line.

Most people write LEFT JOIN and nobody is confused by it, which is a fair reason to leave OUTER out. Be consistent either way. A file that mixes both spellings makes a reader stop and check whether the difference was deliberate.

Now let's turn it around with RIGHT JOIN

A RIGHT JOIN keeps every row of the table on the right of the keyword. Same mechanism, other direction. So this time it is DEPARTMENTS that is guaranteed to survive in full.

This query selects the join key from both tables, aliasing the department side as D_DEPT_ID, because that is the only way to see the two of them come apart.

Query
SELECT E.FIRST_NAME, E.DEPT_ID, D.DEPT_ID AS D_DEPT_ID, D.DEPT_NAME
FROM EMPLOYEES E
RIGHT JOIN DEPARTMENTS D ON E.DEPT_ID = D.DEPT_ID
ORDER BY D.DEPT_ID, E.EMP_ID;
Result8 rows · 4 columns
FIRST_NAMEDEPT_IDD_DEPT_IDDEPT_NAME
Aisha1010Engineering
Marcus1010Engineering
Daniel1010Engineering
Lena2020Finance
Tomas2020Finance
Priya3030Marketing
Sofia3030Marketing
NULLNULL40Operations

There is Operations on the last row: a real department ID in D_DEPT_ID, and NULL in both FIRST_NAME and DEPT_ID. The invented row has swapped sides. It is the employee that does not exist now.

And Grace is not in this result at all. The RIGHT JOIN made no promise about the left table, so her unmatched row was dropped exactly as the inner join dropped it.

LEFT JOINRIGHT JOIN
Table kept in fullEMPLOYEESDEPARTMENTS
Rows returned88
Gracepresent, department columns NULLnot in the result
Operationsnot in the resultpresent, employee columns NULL
Same number, different rows

Both joins returned 8 rows. The seven matched employees are the same seven in both, but the eighth row is not: one result ends with Grace and the other with Operations, and neither contains the other's. The count was identical and told you nothing.
A matching row count is not a check. When you change a join and the count stays the same, that is not evidence the change was harmless.

In practice most people write LEFT JOIN and swap the table order instead of reaching for RIGHT JOIN. Both are correct. The left-hand form is simply easier to read, because the table you care about keeping is the first one you see.

Now let's ask what is missing

This is the thing outer joins earn their keep for, and it is not obvious from the syntax. Keep everything, then filter down to the rows that came back NULL. What we are left with is precisely the rows that found no match.

Query — employees with no department
SELECT E.FIRST_NAME, E.DEPT_ID
FROM EMPLOYEES E
LEFT JOIN DEPARTMENTS D ON E.DEPT_ID = D.DEPT_ID
WHERE D.DEPT_ID IS NULL;
Result1 row · 2 columns
FIRST_NAMEDEPT_ID
GraceNULL

Grace, and only Grace. The WHERE D.DEPT_ID IS NULL test is true exactly when the join manufactured a NULL department row, which is exactly when there was no match.

Now let's point the same shape the other way, and ask the mirrored question.

Query — departments with no employees
SELECT D.DEPT_ID, D.DEPT_NAME
FROM EMPLOYEES E
RIGHT JOIN DEPARTMENTS D ON E.DEPT_ID = D.DEPT_ID
WHERE E.EMP_ID IS NULL;
Result1 row · 2 columns
DEPT_IDDEPT_NAME
40Operations

Operations. The pattern is called an anti-join, and once you recognise it you will see it everywhere: orders with no shipment, users who never logged in, products that have never sold.

Pick the right column to test

Test a column that cannot be NULL in the source table — a primary key is the usual choice, which is why the second query filters on E.EMP_ID rather than on E.DEPT_ID.
Filter on a nullable column and you cannot tell “the join found nothing” apart from “the join found a row and that row's value happens to be NULL”. The query still runs. The answer is just wrong.

Let's try it on a real question: who has never ordered?

Nothing about this is specific to employees. The sample data also has CUSTOMERS and ORDERS, at 10 and 41 rows respectively per the demo script's own row counts, joined on CUSTOMER_ID.

Same anti-join, real question.

Query — customers with no orders at all
SELECT C.CUSTOMER_ID, C.CUSTOMER_NAME, C.COUNTRY
FROM CUSTOMERS C
LEFT JOIN ORDERS O ON C.CUSTOMER_ID = O.CUSTOMER_ID
WHERE O.ORDER_ID IS NULL
ORDER BY C.CUSTOMER_ID;
Result2 rows · 3 columns
CUSTOMER_IDCUSTOMER_NAMECOUNTRY
108Copper Kettle LtdUK
110Sable InteriorsUSA

2 customers have never ordered anything. That is a list somebody in sales would like to have, and an inner join could not have produced it. An inner join returns the customers who did order, and silence about everyone else.

Have a look at the column being tested: O.ORDER_ID, the orders table's own key. Same rule as before.

Now let's count over an outer join

Let's count the orders per customer over a left join, and do it twice in one query. Once with COUNT(*), and once with COUNT of a column from the orders side.

Query — two counts over the same left join
SELECT C.CUSTOMER_NAME,
       COUNT(*) AS COUNT_STAR,
       COUNT(O.ORDER_ID) AS COUNT_ORDERS
FROM CUSTOMERS C
LEFT JOIN ORDERS O ON C.CUSTOMER_ID = O.CUSTOMER_ID
GROUP BY C.CUSTOMER_NAME
ORDER BY COUNT_ORDERS, C.CUSTOMER_NAME;
Result10 rows · 3 columns
CUSTOMER_NAMECOUNT_STARCOUNT_ORDERS
Copper Kettle Ltd10
Sable Interiors10
Vantage Media33
Delta Print Co44
Harbour Foods44
Alpine Logistics55
Kestrel Analytics55
Meridian Health55
Blue Ridge Supply66
Northwind Traders99

Look at the first two rows. COUNT_STAR says those customers have an order. COUNT_ORDERS says they have none. They are the same 2 customers the anti-join just identified, and the anti-join was right.

COUNT(*) counts rows, and the left join manufactured a row for each of those customers so that they would not disappear. A row full of NULLs is still a row, so COUNT(*) counted it.

COUNT(O.ORDER_ID) counts non-NULL values of that column. The manufactured row has no order ID, so it contributes nothing, and the answer is the truthful one.

Watch out

Over an outer join, COUNT(*) is almost always the wrong choice. Count a column that comes from the outer side of the join — the side that may be missing — and the manufactured rows count themselves out.

Every other customer in that grid has the two counts in agreement, which is precisely why this is dangerous. The column looks correct almost everywhere, and it is wrong exactly where the answer mattered.

Now let's add a condition, and watch the outer join undo itself

This is the one that bites hardest. The requirement is ordinary: every customer, with their orders above 5000. Here is the obvious way to write it.

Query — the condition in WHERE
SELECT C.CUSTOMER_NAME, O.ORDER_ID, O.AMOUNT
FROM CUSTOMERS C
LEFT JOIN ORDERS O ON C.CUSTOMER_ID = O.CUSTOMER_ID
WHERE O.AMOUNT > 5000
ORDER BY C.CUSTOMER_ID, O.ORDER_ID;
Result20 rows · 3 columns
CUSTOMER_NAMEORDER_IDAMOUNT
Northwind Traders10036150.00
Northwind Traders10065020.00
Northwind Traders10118100.00
Northwind Traders10175540.00
Northwind Traders10236730.00
Northwind Traders10297460.00
Northwind Traders10358820.00
Northwind Traders10409640.00
Alpine Logistics10077890.00
Alpine Logistics10136420.00
Alpine Logistics10197015.00
Alpine Logistics10268340.00
Alpine Logistics10336900.00
Meridian Health10159250.00
Meridian Health102010400.00
Meridian Health102511200.00
Meridian Health103212850.00
Meridian Health103713100.00
Vantage Media10305180.00
Vantage Media10385930.00

20 rows, and every one of them belongs to one of just 4 customers. There are 10 customers in the table. 6 customers vanished from a query written specifically to keep all of them.

Here is the sequence. The LEFT JOIN did its job and kept every customer, filling the unmatched ones with manufactured NULL order rows. Then WHERE ran, and asked each surviving row whether O.AMOUNT > 5000. For a manufactured row, AMOUNT is NULL, and NULL > 5000 is not true, so the row was thrown out.

The WHERE clause turned the left join back into an inner join. Nothing errored. Nothing warned.

Now let's move the condition into ON

Query — the condition moved into ON
SELECT C.CUSTOMER_NAME, O.ORDER_ID, O.AMOUNT
FROM CUSTOMERS C
LEFT JOIN ORDERS O ON C.CUSTOMER_ID = O.CUSTOMER_ID AND O.AMOUNT > 5000
ORDER BY C.CUSTOMER_ID, O.ORDER_ID;
Result26 rows · 3 columns
CUSTOMER_NAMEORDER_IDAMOUNT
Northwind Traders10036150.00
Northwind Traders10065020.00
Northwind Traders10118100.00
Northwind Traders10175540.00
Northwind Traders10236730.00
Northwind Traders10297460.00
Northwind Traders10358820.00
Northwind Traders10409640.00
Blue Ridge SupplyNULLNULL
Kestrel AnalyticsNULLNULL
Harbour FoodsNULLNULL
Alpine Logistics10077890.00
Alpine Logistics10136420.00
Alpine Logistics10197015.00
Alpine Logistics10268340.00
Alpine Logistics10336900.00
Delta Print CoNULLNULL
Meridian Health10159250.00
Meridian Health102010400.00
Meridian Health102511200.00
Meridian Health103212850.00
Meridian Health103713100.00
Copper Kettle LtdNULLNULL
Vantage Media10305180.00
Vantage Media10385930.00
Sable InteriorsNULLNULL

26 rows, and all 10 customers are present. 6 of them carry NULL in the order columns, which is the honest answer: those customers exist and have no order above the threshold.

Where the condition goesWhat it decidesRowsCustomers in the result
ON … AND O.AMOUNT > 5000What counts as a match2610
WHERE O.AMOUNT > 5000What survives after the join204

That is the entire distinction, and it is worth memorising in exactly those words. In ON, a condition decides what matches. In WHERE, it decides what survives.

A rule of thumb

A condition on the outer table — the one that may be missing — usually belongs in ON. A condition on the table you are keeping in full belongs in WHERE, where it behaves the way you expect.
The exception is deliberate: WHERE <outer column> IS NULL is the anti-join, and it works precisely because WHERE runs after the join.

Key points

  • LEFT JOIN keeps every row of the left table; RIGHT JOIN keeps every row of the right. The unmatched side comes back as NULL.
  • Those NULLs are manufactured by the join, not read from a table. No row of NULLs exists in DEPARTMENTS.
  • OUTER is optional: LEFT JOIN and LEFT OUTER JOIN are identical.
  • The left and right joins here both return 8 rows and they are different rows. A row count is not a check.
  • Keep everything, then filter to the manufactured NULLs, and you have an anti-join — the query that answers “what is missing?”
  • Test a column that cannot be NULL in the source, normally a primary key, or the anti-join cannot tell absence from a stored NULL.
  • COUNT(*) over an outer join counts the manufactured row. COUNT(column) from the outer side does not.
  • In ON a condition decides what matches; in WHERE it decides what survives. A WHERE condition on the outer table silently turns an outer join back into an inner one.
  • Both traps produce queries that succeed. The only defence is knowing where the NULLs came from.
Next in this series

Episode 26 — FULL OUTER JOIN. Both sides kept at once, manufactured NULLs appearing in either direction, and how to tell the three kinds of row in the result apart once you can no longer assume which side is which.

Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the shared sample-data script for this course. The EMPLOYEES, DEPARTMENTS, CUSTOMERS and ORDERS data is invented demo data created by that script. No performance claims are made anywhere in this series — nothing about which side Snowflake reads first, or whether one join direction is cheaper than another, was measured, so nothing about it is said. Clause behaviour is described from the Snowflake JOIN documentation.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.