13. The LEFT JOIN that a WHERE clause quietly undoes

SQLEasyNULL trap

left join · on vs where · count · coalesce

How the Colab notebook works

The notebook has the data, an answer cell and a check() function. You need a Google account; nothing is installed on your machine. Free Colab runs only two or three notebooks at a time, so end the session of a finished problem (Runtime > Disconnect and delete runtime) before opening the next one. "Mark as solved" is remembered in this browser only.

The situation

Account managers get a monthly list of all their customers with how much each one bought. Customers who bought nothing matter most on that list, because those are the ones to call.

Last month's list was short. Every customer on it had bought something.

Input tables

customers

One row per customer.

Column Type Description
customer_id BIGINT Unique per customer.
name STRING Customer name.
city STRING Customer city.

orders

One row per order.

Column Type Description
order_id BIGINT Unique per order.
customer_id BIGINT The customer who ordered. A few orders belong to customers that are not in customers.
order_date DATE Date of the order.
status STRING COMPLETED, CANCELLED or PENDING. Can be NULL.
amount DECIMAL(10,2) Order value in rupees.

Requirement

Return every customer in customers with their completed orders of March 2025.

  • Only orders with status = COMPLETED and an order_date from 1 March 2025 to 31 March 2025 (both included) count.
  • completed_orders is the number of such orders. completed_amount is their total.
  • A customer with no such order still appears, with completed_orders = 0 and completed_amount = 0.00.
  • Orders of customers that are not in customers are ignored.

Expected output

One row per customer in customers.

Column Type Description
customer_id BIGINT
name STRING
completed_orders BIGINT 0 if none.
completed_amount DECIMAL(12,2) 0.00 if none.

Solve it in the browser

This editor runs DuckDB inside your browser. Nothing is installed and nothing is sent to a server. DuckDB's SQL is close to Spark SQL but not identical. The Colab notebook runs real Spark.

query.sql DuckDB, in your browser
Ctrl + Enter runs the query

Your result appears here. Your draft is kept in this browser.

Explanation

Show explanationGives the answer away. Try the problem first.

The approach

A LEFT JOIN keeps every row of the left table. For a customer with no matching order, it produces one row with NULL in every orders column.

What happens to that row next depends on where the conditions are.

In the ON clause, a condition decides which orders count as a match:

FROM customers c
LEFT JOIN orders o
    ON o.customer_id = c.customer_id
    AND o.status = 'COMPLETED'
    AND o.order_date >= DATE '2025-03-01'
    AND o.order_date < DATE '2025-04-01'

A customer with no completed March order matches nothing and keeps their row, with NULLs. That is the row the report needs.

In the WHERE clause, the same condition is applied after the join, to the joined rows:

FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.status = 'COMPLETED' ...

For the customer with no orders, o.status is NULL. NULL = 'COMPLETED' is not true, so the row is removed. The LEFT JOIN did its job and the WHERE threw the result away. The query now behaves exactly like an inner join.

The rule: conditions on the right table of a left join belong in ON. Conditions on the left table belong in WHERE.

The rest of the query is two more NULL details:

  • COUNT(o.order_id) counts matched orders. COUNT(*) would count the NULL row too.
  • SUM over no rows is NULL, so it is wrapped in COALESCE(..., 0).

There are 40 customers. 18 of them have no completed order in March.

Common wrong answers

The conditions in WHERE. Returns 22 rows. The 18 customers with nothing to show are gone, and those were the ones the account managers wanted.

COUNT(*). Returns 40 rows, but every customer with no orders shows completed_orders = 1. The NULL row is still a row.

No COALESCE. completed_amount is NULL instead of 0.00 for those 18 customers.

status <> 'CANCELLED' instead of = 'COMPLETED'. Counts PENDING orders as completed. It also shows why negative conditions are risky with NULLs: an order with a NULL status is not counted either way, because NULL <> 'CANCELLED' is NULL. If the intent was "everything except cancelled", those orders would be silently lost.

Starting from orders. Any query that begins FROM orders can only return customers who have orders. It returns 23 rows here, one of them for customer 9999, who is not in customers at all.

The PySpark version of the same bug

customers.join(orders, "customer_id", "left").filter(F.col("status") == "COMPLETED")

A filter after a left join is a WHERE. Filter orders first, then join.

Edge cases in the data

Case Customers What it catches
No orders at all 1037 to 1040 Conditions in WHERE; COUNT(*).
March orders, all cancelled 1035 Conditions in WHERE.
March orders with PENDING or NULL status 1036 status <> 'CANCELLED'.
Completed orders on 28 February and 1 April 1034 A date range that is one day too wide.
Completed orders on 1 March and 31 March 1033 A date range that is one day too narrow.
Orders for a customer not in customers 9999 Driving the query from orders.