SQL Dojo
Modeling

Surrogate keys that stay put

A key the warehouse owns for each dimension row, so facts never depend on a source's id, and it must come out the same on every rebuild.

Facts point to a dimension through a key the warehouse owns, not the source's id: a second source with its own customer 42 then breaks nothing, and a type 2 history can give one customer several rows. Whatever makes that key, every rebuild must give each row the same one.

SELECT md5(CAST(customer_id AS VARCHAR)) AS customer_key,  -- same input, same key, every night
       customer_id, city, country
FROM customers
UNION ALL
SELECT '-1', -1, 'Unknown', 'Unknown';                     -- the unknown member

Facts whose customer is unknown get '-1' instead of a NULL key that an inner join would drop.

The trap. ROW_NUMBER() OVER (ORDER BY customer_id) numbers positions in a sort: a new customer sorted into the middle shifts every key after it, and the facts loaded before now point to someone else, with no error and the same grand total. Hash the natural key, or keep an identity column on a table you only ever append to. With several parts, md5(a || '-' || b) is NULL as soon as one part is NULL: replace NULL parts first.

In dbt. {{ dbt_utils.generate_surrogate_key(['source_system', 'customer_id']) }} does all that: it casts each part to text, replaces a NULL by a fixed placeholder, joins the parts with '-' and hashes them in each warehouse's own spelling (TO_HEX(MD5(…)) on BigQuery, whose MD5 returns bytes). A table model is recreated on every run and would restart an identity column, so hashing is the usual choice.

WITH oct31(customer_id) AS (VALUES ('cus_1Ab'), ('cus_3Zt'), ('cus_5Kw')),
nov03(customer_id) AS (VALUES ('cus_1Ab'), ('cus_3Zt'), ('cus_4Mq'), ('cus_5Kw')),
keys_oct31 AS (SELECT customer_id, ROW_NUMBER() OVER (ORDER BY customer_id) AS key_oct31 FROM oct31)
SELECT n.customer_id,
       k.key_oct31,
       ROW_NUMBER() OVER (ORDER BY n.customer_id) AS key_nov03,
       md5(n.customer_id) AS hashed_key
FROM nov03 n
LEFT JOIN keys_oct31 k ON k.customer_id = n.customer_id
ORDER BY n.customer_id;
customer_idkey_oct31key_nov03hashed_key
cus_1Ab11dd9714f762a99d6b49a40ff5478225ae
cus_3Zt22164b1381864bf19b466e936fb2dce8e0
cus_4MqNULL333525f785a334838561106fc0b6cd1c2
cus_5Kw34e3538e568f2f68cdede3d2ec0d295fc7
Try it in Randori