19. Which tier was the customer in when they ordered?

SQLMediumBoundary trap

scd2 · slowly changing dimension · point-in-time join · range join · between

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

Customers move between loyalty tiers over time. customer_dim keeps the history as a type 2 slowly changing dimension: one row per period during which a customer stayed in one tier.

Marketing wants to know how much each tier spends. For that, every order has to carry the tier the customer was in on the day of the order, not the tier they are in today.

Input tables

customer_dim

One row per tier period of a customer.

Column Type Description
customer_id BIGINT The customer.
tier STRING SILVER, GOLD or PLATINUM.
valid_from DATE First day of the period.
valid_to DATE The day the period ended. The customer was no longer in this tier on that day. NULL for the customer's current period.

A customer's periods never overlap. Usually the next period starts on the day the previous one ends, but a customer can also have been out of the programme for a while.

orders

One row per order.

Column Type Description
order_id BIGINT Unique per order.
customer_id BIGINT The customer who ordered. Not every customer is in customer_dim.
order_date DATE Date of the order.
amount DECIMAL(10,2) Order value in rupees.

Requirement

Return every order exactly once, with the customer's tier on the order date.

  • A period covers valid_from and every later day before valid_to. An order placed on the day a customer changes tier belongs to the new tier.
  • A period with a NULL valid_to covers every day from valid_from onwards.
  • If no period of the customer covers the order date, tier is NULL. That happens for orders before the customer's first period, during a break in the programme, and for customers that are not in customer_dim.

Expected output

One row per order.

Column Type Description
order_id BIGINT
customer_id BIGINT
order_date DATE
amount DECIMAL(10,2)
tier STRING The tier on the order date. NULL if no period covers it.

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

Each row of an SCD2 table describes a period. Joining a fact to it means finding the one period that contains the fact's date. That is a join on the key plus a range condition:

FROM orders o
LEFT JOIN customer_dim d
    ON d.customer_id = o.customer_id
    AND d.valid_from <= o.order_date
    AND (d.valid_to IS NULL OR o.order_date < d.valid_to)

Three decisions are in those lines.

The lower bound is inclusive, the upper bound is exclusive. The table says valid_to is the day the period ended and the next one began. A period therefore covers valid_from <= date < valid_to. With this convention the periods fit together without overlapping, and every date belongs to exactly one of them.

The current period has no end. Its valid_to is NULL. order_date < NULL is not true, so without the IS NULL branch no order would ever match a current period.

It is a left join. An order that no period covers still has to appear, with a NULL tier.

There are 199 orders. 44 of them have no tier: they were placed before the customer's first period, during a break, or by a customer who is not in the dimension.

Common wrong answers

BETWEEN valid_from AND valid_to. Returns 209 rows. BETWEEN includes both ends. On the day a customer changes tier, the old period's valid_to and the new period's valid_from are the same date, so an order on that day matches both periods and appears twice, once with each tier. Nothing fails; revenue is simply counted twice for those orders. This is the most common bug in SCD2 joins.

Forgetting the NULL valid_to. Row count is right, tiers are wrong: every order that falls in a customer's current period gets NULL. Since current periods cover the most recent orders, the newest data is the data that goes missing.

Inner join. Returns 155 rows. The 44 orders without a period are dropped, and so is their revenue.

Joining to the current tier (is_current, or valid_to IS NULL). Assigns every order the tier the customer has today. 91 of the 199 orders get a different answer. This rewrites history: a customer who was SILVER when they bought and is PLATINUM now has all their old spending counted as PLATINUM spending.

Joining on customer_id alone. Returns 488 rows: every order once for every period the customer ever had.

valid_from < order_date. An order on the first day of a period finds no period.

Know the convention of your table

This table uses an exclusive valid_to. Many warehouses use an inclusive one, where a period ending on 31 March is followed by one starting on 1 April, and some use a far future date such as 9999-12-31 instead of NULL for the current row. With an inclusive end date, BETWEEN is correct. Read the table's documentation, or look at two consecutive rows of one customer, before writing the join. The exclusive convention has one advantage: it also works for timestamps, where "one day before" has no clean meaning.

Edge cases in the data

Case Where What it catches
Order on the day the tier changed 10 orders BETWEEN matches two periods.
Order in the customer's current period many orders Missing valid_to IS NULL.
Order before the customer's first period many orders Inner join.
Order on the first day of a period customers 703, 711, 720 < instead of <= on valid_from.
A break between two periods customer 728, March to May Assuming periods are always contiguous.
Customer not in the dimension customer 799 Inner join.