Grain first
Part of the free LogicWiz Data Engineering course, Module 5: Data modelling. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:05 on Monday. Tess has built a new table, order_report, by joining orders, order lines and payments. It says SwiftKart captured $27,176.56 in June. The payment provider's statement says $8,514.73. Nothing failed. Nora looks at the table and asks one question: "What does one row mean?"
You'll learn to
- Say what one row of a table means, in one sentence
- Prove it by counting rows against distinct keys
- Spot the join that quietly changes what a row means
- Choose a counter or a hash as the warehouse's own key
Learn
One row means one thing
Tess cannot answer Nora's question, and that is the bug.
Every table makes a quiet promise: each row stands for one thing. One order. One line of an order. One customer on one day. That promise is called the grain of the table, and you say it as a plain sentence: "one row per order line".
The grain decides everything else. It tells you which columns belong (an order line has a product, an order does not), which key must never repeat, and which numbers are safe to add up.
Think of a till receipt: one line per item, one total at the bottom. Copy the total onto every line and the receipt no longer adds up.
What one row means in the shop's tables
Six source tables, each with the sentence for its grain and its key; order 1033 is drawn as one row in orders, two rows in order_items and two rows in payments.
Read each box as a sentence: "payments has one row per payment attempt". The small boxes are the rows of one order, 1033. A table's name can mislead: customers is one row per sign-up, not per person (Maya Chen signed up three times), and payments holds every attempt, failed, captured or refunded.
Test the promise with two counts
A grain is a promise, so test it.
If order_items really has one row per order line, the pair (order_id, line_no) must never repeat. Count the rows. Count the distinct pairs. When the two numbers match, the promise holds.
The second query below is the one you keep in your pipeline. It lists every key that appears more than once, so an empty result means the grain is clean. A unique test in dbt (Module 8) runs this same query behind the scenes.
Two counts, then the duplicates
SELECT
COUNT(*) AS line_rows,
COUNT(DISTINCT (order_id, line_no)) AS distinct_lines
FROM order_items;
SELECT order_id, line_no, COUNT(*) AS copies
FROM order_items
GROUP BY order_id, line_no
HAVING COUNT(*) > 1;
Both counts are 201, and the second query returns no rows: the grain holds. COUNT(DISTINCT (order_id, line_no)) counts distinct pairs.
Payments has a row for every attempt
Now the clue. Tess wanted one row per order with its payment. But look at payments in the picture above: one row per attempt.
Order 1012 failed on a card, then paid with a wallet: two rows. Order 1033 was charged twice by mistake: two rows. Every returned order has a captured row and a refunded row.
So when you join orders to payments, an order comes back once per payment. The result still looks like a table of orders. It is not one any more. A join can change the grain, and it never tells you.
Before you count the rows, try one join in your head.
Count the rows after every join
SELECT 'orders' AS step, COUNT(*) AS row_count
FROM orders
UNION ALL
SELECT 'orders + payments', COUNT(*)
FROM orders
JOIN payments USING (order_id)
UNION ALL
SELECT 'orders + lines + payments', COUNT(*)
FROM orders
JOIN order_items USING (order_id)
JOIN payments USING (order_id);
80 orders become 85 rows with the payments, then 216 with the order lines as well. Counting after every join is the cheapest bug detector you will ever use.
Order 1033 through Tess's two joins
Order 1033 starts as one row, becomes two rows when payments are joined, four rows when order lines are joined, and one row again when each table is summed per order before the join.
Start with the order. Order 1033 is one row in
orders. It has two lines, sunglasses and hand cream, and is worth $91.25. It was charged twice by mistake.Join payments. Two captured payments, so the order comes back twice: one row per payment.
SUM(amount)says $182.50. That is true so far: the double charge is real money.Join the order lines. Two lines times two payments is four rows. Each payment is now repeated once per line, so
SUM(amount)says $365.00 for an order worth $91.25.The fix: sum first, then join. Add the lines up to one row per order. Add the captured payments up to one row per order. Now both sides have the same grain, the join is one to one, and nothing repeats.
Read the right-hand box: its heading counts the rows and gives the sum. Repeats like the red rows, across all the orders, are how $8,514.73 became $27,176.56.
Four SwiftKart orders joined to their payments: order 1012 has a failed and a captured payment, so it appears twice and its total counts twice, until payments are added up to one row per order before the join.
Your turn. Watch the row count and the sum under "After the join", then tick the fix: payments are added up per order first, and order 1012 goes back to one row.
The trap: writing the joins first, and finding out the grain from the result. Write one sentence first ("one row per order line, for every order ever placed"). Then check COUNT(*) against COUNT(DISTINCT key) after every join. When the two drift apart, the grain changed under you.
Two keys for one customer
Nora has a second question: which column should warehouse tables join on?
The shop already has ids: order_id, a product sku, an email. A key that comes from the source system is a natural key. People can read it.
The warehouse also makes up a number with no meaning at all: customer_key 1, 2, 3. That is a surrogate key. Why add one?
- History. Jonas Weber, customer 18, moved from Berlin to Munich. The warehouse keeps both versions of him, and each needs its own key.
- Many sources. The shop and a store it buys can both have a customer 18.
- Stability. Source systems recycle or reformat ids.
Keep both: join on the surrogate key, trace a row back with the natural key.
Customer 18 has two rows
SELECT customer_key, customer_id, name, city, valid_from, valid_to
FROM dim_customer
WHERE customer_id = 18
ORDER BY valid_from;
This runs on the warehouse, swiftkart_dw. The grain of dim_customer is one row per version of a customer. So customer_id 18 appears twice, and the surrogate customer_key (18, then 19) is the column that stays unique. Lesson 5.4 builds this table.
A counter depends on who came first
How does the warehouse make up a key? The usual way is a counter. The first row gets 1, the next gets 2, like tickets at a bakery counter.
A counter key is a whole number of 4 or 8 bytes. Consecutive numbers compress to almost nothing, and no key is cheaper to join on.
Its weakness: the number depends on who arrived first. Rebuild dim_customer from scratch with the rows in a different order, and Maya gets key 7 instead of 2. Every fact that stored 2 now points at someone else. So facts and dimensions must be rebuilt together.
Step through it below. The last step shows the other kind of key.
Rebuild the dimension: counter against hash
A customer table is built with counter keys, rebuilt in a different order so the keys change and a fact row points at the wrong customer, then rebuilt with hash keys that stay the same.
First build, with a counter. Rows load in sign-up order. Maya Chen, customer 2, gets key 2. One of her order lines stores that 2.
Rebuild from scratch. The rows arrive in a different order. Maya is now key 7, and key 2 belongs to Alex. The fact row still says 2, so Maya's order now belongs to Alex. Nothing errors.
The same rebuild, with a hash key. The key is computed from
customer_id.md5('2')starts withc81e728don every build, in any order. Maya keeps her key, and the fact row still points at her.
Watch the fact row on the right. It is never rewritten, so everything depends on the dimension giving Maya the same key again. The new counter keys are made up for the example; the md5 prefixes are real.
A hash is computed, not looked up
The last step used a hash key: a key computed from the natural key itself. md5(customer_id), or md5(order_id || '-' || line_no) when the key has two parts. Same input, same key, on every build. It is a fingerprint, not a ticket.
That buys two more things:
- No lookup. With a counter, the fact loader must join to the dimension to swap
customer_idforcustomer_key, so the dimension has to load first. With a hash, the fact loader computes the key in its own pipeline. - No shared counter. Two sources can make the same key without talking to each other.
The price is size. Look at the bars.
One key column on 730 million fact rows
Bars compare the raw size of one key column on 730 million fact rows: 2.92 GB as INT, 5.84 GB as BIGINT, 11.68 GB as 16-byte MD5 binary and 23.36 GB as 32-character MD5 text.
A longer bar is more bytes. 730 million rows is one year at 2 million order lines a day. These sizes are before compression: the integers then shrink a lot, the hashes hardly at all, because hash values look random. Every join compares the wider values too. Store a hash as binary when the engine allows it.
Can two customers get the same hash?
A hash squeezes any input into a fixed number of bits. So two different customers can land on the same value. That is a collision, and nothing warns you: two customers share a key and their orders merge.
How likely is it? Think of birthdays. In a room of 23 people, two share a birthday more often than not, because every pair gets a chance to match.
For n keys and a hash of b bits, the chance is about p ≈ 1 − e^(−n² / 2^(b+1)). It is called the birthday bound. Work it once, for a 64-bit hash and one billion customers:
- n² = 10^18
- 2^65 ≈ 3.69 × 10^19
- n² / 2^65 ≈ 0.027
- p ≈ 1 − e^(−0.027) ≈ 2.7%
Chance that at least two keys collide
| Keys | 32-bit | 64-bit | 128-bit (MD5) |
|---|---|---|---|
| 100,000 | 69% | 2.7 × 10⁻¹⁰ | 1.5 × 10⁻²⁹ |
| 100 million | certain | 0.027% | 1.5 × 10⁻²³ |
| 1 billion | certain | 2.7% | 1.5 × 10⁻²¹ |
| 10 billion | certain | 93% | 1.5 × 10⁻¹⁹ |
Read across a row: more bits, smaller chance. The numbers come from the formula above. A large clickstream table passes 10 billion rows in a year, so a 64-bit hash is fine for sorting rows into buckets but not for keys. 128-bit MD5 is safe in practice.
Two ways to build a hash key wrong
Most hash-key bugs are not bad luck. The code builds them.
No separator. Order 101 line 23 and order 1012 line 3 both glue together as 101233. Same text, same hash, same key.
A NULL part. In SQL, || with a NULL gives NULL. One missing part and the whole key is NULL.
The cure is the same every time: put a separator between the parts, and swap NULL for a placeholder before you hash. Run the query. The first column is the collision; the last is a safe key.
A collision the code built
SELECT
md5('101' || '23') = md5('1012' || '3') AS no_separator_collides,
md5(concat_ws('-', '101', '23')) = md5(concat_ws('-', '1012', '3')) AS with_separator_collides,
md5('1048' || NULL) IS NULL AS null_makes_the_key_null,
md5(concat_ws('-', '1048', COALESCE(NULL, '_null_'))) AS safe_key;
Without a separator the two keys collide; with one they differ. A NULL part makes the whole key NULL, until COALESCE swaps it for a placeholder.
How dbt_utils.generate_surrogate_key builds a key
Five steps: take the key columns, cast each to text, replace NULL with a placeholder, join the parts with a hyphen, and hash the result with MD5 into 32 hex characters.
Read it left to right: the amber step closes the NULL hole, the next one the separator hole. This dbt macro does the same on every warehouse, so projects on Snowflake, BigQuery and Databricks compute identical keys from identical inputs.
Remember: a counter key is small but depends on load order. A hash key is the same on every build but wider. Whichever you pick, put a unique test on it.
Numbers to remember
| What | The number | Why it matters |
|---|---|---|
| MD5 | 128 bits: 16 bytes as binary, 32 characters as hex text | md5() in Postgres returns the 32-character text |
| 32-bit hash (Spark's hash()) | 50% chance of a collision at about 77,000 keys | Never a key |
| 64-bit hash (Spark's xxhash64, BigQuery's FARMFINGERPRINT, Snowflake's HASH) | 2.7% at 1 billion keys | Snowflake's documentation says: do not use HASH to create unique keys |
| 128-bit MD5 | about 1.5 × 10⁻²¹ at 1 billion keys | Broken for security, fine for keys: a key only needs values spread evenly |
| Counter keys | Postgres: an IDENTITY column or a sequence. Snowflake: a sequence or AUTOINCREMENT. Databricks: GENERATED ALWAYS AS IDENTITY | Unique, not gap-free. On Delta Lake an identity column disables concurrent transactions on its table |
| Hash key of a type 2 dimension | hash the natural key plus validfrom | Each version of a customer needs its own key (Lesson 5.4) |
| Kimball's four design steps | process, grain, dimensions, facts | The grain comes second, before any column. Lesson 5.3 uses all four |
Hash keys let facts and dimensions load at the same time. Data Vault relies on that (Lesson 5.6).
What changed at SwiftKart
Tess rebuilds order_report at one row per order: she sums the lines per order, sums the captured payments per order, then joins. The report now says $8,514.73, the same as the payment provider. It also shows that order 1033 paid twice, so finance can refund it.
The model file now starts with a sentence, "one row per order", and a unique test on the key checks it on every run.
You know what a row means. Lesson 5.2 asks what the numbers in a row mean: which ones you may add up, and which ones lie when you do.
In one line
Say what one row means before you write SQL, count rows against distinct keys after every join, and give the warehouse its own key: a counter or a hash.
Interview corner
What is the grain of a table, and why does it matter?
The grain is what one row represents, such as one row per order line. It decides which columns belong in the table, which key must be unique and which measures can be summed. Mixing grains, for example order totals on a line-level table, is the most common reason a report double counts.
Natural key or surrogate key: when do you need a surrogate key?
A natural key comes from the source (an order id, a SKU); a surrogate key is a meaningless number the warehouse assigns. You need a surrogate when one natural key needs several rows (type 2 history), when several sources could reuse the same id, or when source ids are unstable. Keep the natural key too, so every row can be traced back.
A revenue number is three times higher than the source. Where do you look first?
At the joins: a one-to-many join changes the grain and repeats the measure. I would count rows and distinct keys after each join to find where they diverge, then aggregate each side to the target grain before joining. Finally I would add a reconciliation check against the source total so it cannot happen silently again.
Sequence or hash surrogate keys for a lakehouse fact that will pass 5 billion rows?
A sequence key is 8 bytes, compresses well and joins fastest, but it depends on load order, forces a dimension lookup before every fact load, and on Delta an identity column blocks concurrent writers. A hash key is deterministic, so rebuilds keep keys and facts can be keyed in parallel with the dimension. I would not use a 64-bit hash there: the birthday bound gives about a 50% collision chance near 5 billion keys. MD5 stored as 16-byte binary is safe (about 4 × 10⁻²⁰), at twice the bytes of a BIGINT, and I would still put a unique test on it.