Keeping LEFT JOIN Intact While Picking One Shipment per Order
SQL & DataModel answerLast updated
Explain why moving a shipment predicate from ON to WHERE turns a LEFT JOIN into an INNER JOIN, then write a query that keeps every qualifying order and attaches only its latest expedited shipment.
Setting
You support a fulfillment analytics pipeline that joins marketplace order data to shipment events.
Two tables are available:
orders:order_id,marketplace_id,seller_id,order_dateshipments:shipment_id,marketplace_id,order_id,carrier,is_expedited(BOOLEAN),shipped_at
Order identifiers are only unique within a marketplace, so every join between these tables must use the composite key (order_id, marketplace_id). A single order may have several shipments, and several of them may be expedited.
Part 1 — Explain the difference
Two reports are in circulation:
-- Report 1
SELECT o.order_id, o.marketplace_id, s.carrier
FROM orders o
LEFT JOIN shipments s
ON o.order_id = s.order_id
AND o.marketplace_id = s.marketplace_id
AND s.is_expedited = TRUE;
-- Report 2
SELECT o.order_id, o.marketplace_id, s.carrier
FROM orders o
LEFT JOIN shipments s
ON o.order_id = s.order_id
AND o.marketplace_id = s.marketplace_id
WHERE s.is_expedited = TRUE;
Describe, in words, how each report behaves:
- Which orders appear in each result?
- How many rows does each report return on the sample data below, and why?
- What happens to an order that has shipments but none of them expedited?
- What happens to an order that has no shipments at all?
- Is there still a risk of duplicated orders even in the report that behaves "correctly"?
Part 2 — Produce the report you actually need
Write a SQL query that satisfies all of the following:
- Every order with
order_date >= '2023-01-01'appears in the output. - The join to
shipmentsuses(order_id, marketplace_id). - Only expedited shipments are eligible.
- If an order has no expedited shipment, the order still appears with
NULLin the shipment columns. - If an order has several expedited shipments, exactly one row is returned for that order — the one with the greatest
shipped_at. - When two expedited shipments share the exact same
shipped_at, the choice must be deterministic (useshipment_idas the tie-breaker).
Sample Data
orders:
| order_id | marketplace_id | seller_id | order_date |
|---|---|---|---|
| 101 | US | S1 | 2023-02-01 |
| 102 | US | S2 | 2023-02-05 |
| 103 | UK | S1 | 2023-02-10 |
shipments:
| shipment_id | marketplace_id | order_id | carrier | is_expedited | shipped_at |
|---|---|---|---|---|---|
| 1 | US | 101 | UPS | TRUE | 2023-02-02 10:00:00 |
| 2 | US | 101 | FedEx | TRUE | 2023-02-02 14:00:00 |
| 3 | US | 102 | USPS | FALSE | 2023-02-06 09:00:00 |
Expected Output
| order_id | marketplace_id | seller_id | carrier | shipped_at |
|---|---|---|---|---|
| 101 | US | S1 | FedEx | 2023-02-02 14:00:00 |
| 102 | US | S2 | NULL | NULL |
| 103 | UK | S1 | NULL | NULL |
Edge Cases
- Orders whose only shipments are non-expedited.
- Orders with no shipment rows whatsoever.
- Two expedited shipments with identical
shipped_at. is_expeditedstored asNULL.shipped_atstored asNULL.NULLinside a join-key column.
What to Submit
Prose explaining the semantics of each report and a single production-ready SQL query for Part 2, plus a brief note on the behavior of the chosen query for each edge case above.
Hints
Hint 1
Ask yourself when each clause is evaluated: ON builds the join, WHERE filters the already-built result set.
Hint 2
A LEFT JOIN manufactures NULLs on the right side for unmatched left rows; a WHERE comparison against NULL yields UNKNOWN, so those rows are discarded.
Hint 3
To guarantee one row per order, first reduce the shipment side to a single winner per composite key (e.g. ROW_NUMBER() partitioned by order_id, marketplace_id), then LEFT JOIN that reduced set.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
The mental model: ON matches, WHERE filters
A LEFT JOIN promises that every left-table row appears in the output. The catch is that this promise covers the left rows only; the right side may be padded with NULLs to make that true. Where you put a predicate on the right table decides whether that padding survives.
- A right-table predicate in the
ONclause restricts which right rows are eligible to match. An order with no eligible shipment is still emitted, padded withNULLs on the right. - A right-table predicate in the
WHEREclause runs after the join has produced its result set, including theNULL-padded rows.NULL = TRUEevaluates toUNKNOWN, andWHEREkeeps only rows that evaluate toTRUE. So the padded rows are silently discarded.
That is why the second report behaves exactly like an INNER JOIN with an expedited filter — the outer-ness is destroyed by the WHERE clause.
Report 1 (is_expedited in ON)
Orders 101 and 102 match on the composite key; order 103 has no shipment at all. Only expedited shipments are eligible to match, so:
- Order 101 matches shipments 1 and 2 → two output rows (UPS, FedEx).
- Order 102's only shipment is not expedited, so it is not eligible → order 102 survives with
carrier = NULL. - Order 103 has no shipment → survives with
carrier = NULL.
Row count = Σ over orders of max(1, count of expedited shipments) = 4 rows on this data.
So Report 1 preserves the outer join, but it is still not usable for a per-order report: order 101 is duplicated because the join is one-to-many. Correct outer semantics, wrong cardinality.
Report 2 (is_expedited in WHERE)
Order 102 matches shipment 3, but is_expedited = FALSE fails the WHERE test, so the row is removed — and with it the only trace of order 102. Order 103's padded row has s.is_expedited = NULL, so NULL = TRUE is UNKNOWN and the row is dropped as well. Only order 101's two expedited shipments survive: 2 rows.
Net effect: the report answers "which orders have an expedited shipment" rather than "for each order, what is its expedited shipment". Orders with only non-expedited shipments and orders with no shipments vanish without any error signal — the classic silent-failure bug.
The safe query
The requirement "at most one shipment row per order" means the right side must be reduced to a single winner before the join. ROW_NUMBER() does that cleanly.
WITH latest_expedited AS (
SELECT
order_id,
marketplace_id,
carrier,
shipped_at,
ROW_NUMBER() OVER (
PARTITION BY order_id, marketplace_id
ORDER BY shipped_at DESC NULLS LAST,
shipment_id DESC
) AS rn
FROM shipments
WHERE is_expedited = TRUE
)
SELECT
o.order_id,
o.marketplace_id,
o.seller_id,
le.carrier,
le.shipped_at
FROM orders o
LEFT JOIN latest_expedited le
ON o.order_id = le.order_id
AND o.marketplace_id = le.marketplace_id
AND le.rn = 1
WHERE o.order_date >= DATE '2023-01-01';
Why each piece sits where it does
is_expedited = TRUE inside the CTE. Filtering the right side before it meets the left side is what keeps the outer join outer. Because the filter never touches the joined result set, no order can be eliminated by it.
PARTITION BY order_id, marketplace_id. The partition must use the full composite key. Partitioning by order_id alone would let a shipment from marketplace UK compete with one from US for the same order id, which is a data-corruption bug, not a cosmetic one.
le.rn = 1 in the ON clause. This predicate must stay in ON. Moving it to WHERE reproduces the original trap: unmatched orders have le.rn = NULL, NULL = 1 is UNKNOWN, and those orders disappear. An equivalent formulation is to filter rn = 1 inside a second CTE and drop the predicate from the join entirely.
order_date >= DATE '2023-01-01' in the WHERE clause. This is the mirror-image trap. A left-table predicate inside ON does not remove left rows; it merely restricts which orders may match, so pre-2023 orders would still be returned with NULL shipment columns. Only the right table needs the careful ON placement; left-table filters belong in WHERE.
Ordering with NULLS LAST, shipment_id DESC. Ordering by shipped_at DESC alone leaves ties unspecified and, in engines where NULLs sort first in DESC order (PostgreSQL and Oracle), would rank an unknown timestamp as "latest". NULLS LAST fixes the null case; shipment_id DESC makes exact timestamp ties deterministic and repeatable across runs and across replicas.
On the sample data this returns order 101 with FedEx at 14:00, and orders 102 and 103 with NULL shipment fields — exactly the expected three-row output.
Edge-case behavior
| Case | Result |
|---|---|
| Order with only non-expedited shipments | Shipment removed by the CTE filter; order returned with NULLs |
| Order with no shipments | No match in the left join; order returned with NULLs |
Two expedited shipments with the same shipped_at | shipment_id DESC picks the higher shipment_id deterministically |
is_expedited IS NULL | Not TRUE, so excluded; order returned with NULLs |
shipped_at IS NULL | Ranked last by NULLS LAST; chosen only if it is the sole expedited shipment |
NULL in a join-key column | NULL = NULL is UNKNOWN, so the rows do not match; the order is returned with NULL shipment fields. Treat a null marketplace_id as a data-quality problem upstream rather than trying to make it join |
Duplicate (order_id, marketplace_id) in orders | Both left rows are returned, each with the same shipment; the query does not dedupe the left table |
Cost
Let O = number of orders, S = total shipments, S_e = expedited shipments.
- Time: the window step sorts within each partition, roughly O(S_e log S_e); the hash join is O(O + S_e).
- Space: O(S_e) for the window partitions and the hash table.
Practical notes
Modern optimizers generally push the is_expedited predicate down to the table scan even in the ON version, so the two forms usually cost the same to execute. The real performance lever is the window step, and the ways to make it cheaper are: filter is_expedited and a shipped_at lower bound as early as possible; semi-join the shipments to the in-scope orders before ranking; cluster or distribute both tables on (order_id, marketplace_id) to avoid a shuffle; and use native top-1 constructs where available (QUALIFY rn = 1 in Snowflake/BigQuery/Databricks, MAX_BY in BigQuery).
For a pandas implementation, the same logic is a filtered sort_values(...).drop_duplicates(subset=keys, keep="first") on the shipment frame followed by merge(..., how="left", validate="one_to_one"); the validate argument makes pandas raise instead of silently duplicating rows if the right side ever stops being unique per key.