R Programming / Analysis interfaces and table integrity / Lesson 14
Check join cardinality before summarizing
Detect duplicate keys before a left join and verify row counts and unmatched records before computing totals.
On this page
Lesson goals
- State the expected key relationship.
- Detect duplicate lookup keys before joining.
- Verify join results and missing matches.
- Predict join row counts from key multiplicities.
- Reconcile lookup coverage, source identities and amount totals.
Define the relationship
A join connects rows by keys, and its row count depends on how many matching rows exist on each side. Suppose each order must match at most one customer. Duplicate customer IDs violate that lookup contract and can duplicate an order amount in the joined output. Decide whether unmatched orders are allowed and whether missing keys have a meaning before choosing a join and summarizing the result.
Observe multiplication
The first block creates two orders and three customer rows, with ID 1 repeated in the customer table. A left merge keeps the orders but produces three joined rows because the first order matches two customer rows. Summing amount after this merge would count that order twice. Inspect duplicate key counts and affected rows rather than assuming that a plausible output total proves correctness.
orders <- data.frame(id = c(1, 2), amount = c(10, 20))
customers <- data.frame(id = c(1, 1, 2), name = c("A", "A2", "B"))
table(customers$id)
joined <- merge(orders, customers, by = "id", all.x = TRUE)
nrow(joined)
ID 1 matches twice, so a left merge produces three rows from two orders.
Stop on a violated lookup contract
The second block uses the objects created in the first block and finds duplicate customer IDs. With the fixture it stops before the merge, because uniqueness is required. In an actual analysis, resolve the source data or explicitly revise the relationship; arbitrarily keeping the first match may discard meaningful information. Also decide how to handle missing IDs and unmatched records, since uniqueness alone does not prove full coverage.
duplicate_ids <- unique(customers$id[duplicated(customers$id)])
if (length(duplicate_ids) > 0) {
stop("Customer id must be unique")
}
safe_join <- merge(orders, customers, by = "id", all.x = TRUE)
The guard deliberately stops for this fixture rather than choosing a customer arbitrarily.
Review the resulting data
After a valid join, compare row counts, distinct order IDs, unmatched keys, and a few representative records against expectations. A row-count match is useful but not sufficient: an incorrect match can preserve the count. Record the join keys and policy in the analysis, and keep diagnostics free of private identifiers when sharing them. Only then compute aggregates, with the missing-value policy made explicit.
Verify with controlled fixtures
Test unique matching keys, a duplicate lookup key, an unmatched order, an empty table, and missing keys under the stated policy. Confirm the duplicate fixture stops before summarization and that a valid fixture preserves the intended order count and amounts. Compare a small expected total by hand. When data originates outside R, validate types and normalize keys consistently before joining, without collapsing distinct IDs accidentally.
Define the relationship and measurement grain
A join is a set of matches between rows sharing an explicit key. Before joining, state what one row means on each side and what one row must mean afterward. An order table may contain several orders for one customer; a customer lookup should have at most one row per customer key. That is a many-to-one relationship from orders to customers. If the lookup has two rows for a key, every matching order is repeated twice. The order amount belongs to the order, so summing the joined rows can inflate revenue even though the left join retained all orders.
For key k with L_k left rows and R_k matching right rows, an inner merge produces L_kΓR_k rows for that key. A left merge additionally preserves each unmatched left row once; it does not constrain the number of right matches. Predict row counts by key before combining data. Count distinct source order IDs independently of customer IDs, because a repeated customer is ordinary when one customer has multiple orders. Document whether an unmatched order is an error, an allowed incomplete lookup or a separately reported category.
Guard and reconcile a small lookup
The synthetic orders 101, 102 and 103 have customers A, B and C and amounts 8, 12 and 5. The lookup has one row each for A and B; C is absent. The code checks missing keys, uniqueness of order IDs and lookup customer IDs before a left merge. A nonmissing present marker on each lookup row distinguishes a real match from an unmatched order even when another lookup field could itself be NA. Sorting by order_id makes the intended display explicit; sort=FALSE alone does not promise source order.
There are three source and three joined rows because the lookup is unique. The source and joined amount totals both equal 25, while order 103 is unmatched. A preserved total does not prove complete coverage: here the amount is still present despite the missing customer. Check known ID-to-region associations as well as counts, amounts and unmatched identities. The code describes a synthetic, in-memory example only. R and Rscript were unavailable during authoring, so the resulting values are reasoned expectations; no parser or runtime execution was performed.
orders <- data.frame(order_id=c(101,102,103), customer_id=c("A","B","C"), amount=c(8,12,5))
customers <- data.frame(customer_id=c("A","B"), region=c("north","south"), present=TRUE)
stopifnot(!anyNA(orders$customer_id), !anyNA(customers$customer_id))
stopifnot(!anyDuplicated(orders$order_id), !anyDuplicated(customers$customer_id))
joined <- merge(orders,customers,by="customer_id",all.x=TRUE)
joined <- joined[order(joined$order_id), , drop=FALSE]
unmatched <- joined$order_id[is.na(joined$present)]
c(source_rows=nrow(orders), joined_rows=nrow(joined), source_total=sum(orders$amount), joined_total=sum(joined$amount))
unmatched
The guards validate keys, then the left merge retains the unmatched order and the marker identifies it.
Diagnose duplicates without inventing a repair
duplicated flags later occurrences relative to earlier ones; anyDuplicated returns the first duplicate position or zero when no duplicate exists. To inspect all rows in a duplicate group, combine forward and reverse duplicated masks or count each key. Check the intended key columns together when identity is composite, such as customer and effective date. A duplicate may be a source error, a legitimate history row, or evidence that the actual key is incomplete. Do not keep the first row merely because it makes a guard pass; a valid repair needs a documented rule and an audit trail.
Missing keys need their own policy. Base R matching can match NA keys, and duplicated treats missing values as equal for its ordinary comparison. Reject unknown IDs or separate them when unknown-to-unknown matches are not meaningful. A uniqueness test alone cannot decide that policy: one missing key can be unique but still invalid. Normalize types, whitespace or case only under an explicit identity contract, then check for collisions introduced by normalization; two distinct identifiers must not be silently collapsed.
Summarize at the right grain
When details genuinely have multiple rows per order, retain them if the goal is a detail-level report, or aggregate them to one row per order under a stated rule before joining an order-level measure. For amounts 3 and 4 belonging to order 101, their line total is 7; a separate header amount must not be repeated and summed for each line. If another child table contains three tags for that order, joining two lines to three tags creates six combinations. Aggregate each child independently to the intended order grain before combining summaries, unless the line-tag combinations are the intended observations.
Distinct-value sums are not a general fix: two different orders can have the same amount, and summing unique amounts would discard one legitimate order. Instead use the source order ID, ensure the expected relationship, and calculate the amount at its original grain. Missing values also affect totals: decide whether a missing amount is unknown, excluded, or otherwise handled rather than treating it automatically as zero. Keep counts of valid, missing and excluded records alongside a total.
Verify coverage, identities and totals together
A useful synthetic test suite covers a unique lookup, a duplicated key, a missing key, an unmatched source row, an empty lookup, multiple child rows and a wrong association that preserves row count. Check the expected count per key and source ID, lookup uniqueness, unmatched IDs, and known associations. Compare source and joined totals only when each source amount should contribute exactly once and missing-value rules agree. An unchanged total can still conceal a dropped amount offset by a duplicated amount; check identities and coverage as separate invariants.
When the contract fails, stop before publishing a summary and surface the affected synthetic keys or privacy-safe counts in a real workflow. Repair source data or revise the relationship explicitly, then rerun the same controls. For a stable report order, retain a source sequence and sort by that sequence plus a child tie breaker when required. Record key definitions, normalization, join arguments, version and missingness policy with the analysis. These checks improve traceability but do not certify the accuracy or provenance of the underlying values.
20 worked examples
1. Unique customer lookup
Problem: Join three orders belonging to customers A,A,B with one lookup row per customer.
- Both A orders each match the single A lookup row.
- The B order matches the single B row, so no source order multiplies.
orders <- data.frame(order=1:3,customer=c("A","A","B"))
lookup <- data.frame(customer=c("A","B"),region=c("N","S"))
nrow(merge(orders,lookup,by="customer",all.x=TRUE))
Expected result: Three joined rows.
Why this result follows: A unique right key permits a many-to-one lookup.
2. Locate duplicate lookup keys
Problem: Find duplicate customer IDs in A,B,A,C before merging.
- The third position repeats the A seen in the first position.
- unique returns the duplicated key once for diagnosis.
keys <- c("A","B","A","C")
unique(keys[duplicated(keys)])
Expected result: A is the duplicated key.
Why this result follows: The guard identifies the key requiring relationship review.
3. Many-to-many count
Problem: Predict an inner join with four left and two right rows for key K.
- Each of four left records matches both right records.
- Multiplying four by two gives eight combinations.
x <- data.frame(key=rep("K",4),left=1:4)
y <- data.frame(key=rep("K",2),right=1:2)
nrow(merge(x,y,by="key"))
Expected result: Eight matched rows.
Why this result follows: Equality merge emits every matching pair for the key.
4. Find unmatched orders
Problem: Identify orders with customer C when lookup keys are A and B.
- A and B appear in the lookup key vector.
- Customer C does not appear, so its order is selected.
orders <- data.frame(order=1:3,customer=c("A","B","C"))
lookup <- data.frame(customer=c("A","B"))
orders$order[!orders$customer %in% lookup$customer]
Expected result: Order 3 is unmatched.
Why this result follows: Coverage must be checked separately from lookup uniqueness.
5. Unique but incomplete
Problem: Check lookup keys A,B for duplicates and coverage of source key C.
- A and B occur once each, so the uniqueness test passes.
- C has no lookup match, so the coverage test fails.
lookup <- c("A","B"); source <- c("A","C")
c(unique=anyDuplicated(lookup)==0, covered=all(source %in% lookup))
Expected result: unique=TRUE and covered=FALSE.
Why this result follows: The two controls protect different properties of the relationship.
6. Default missing-key match
Problem: Predict the inner merge of two rows whose single keys are both NA.
- The default R match behavior treats these missing keys as matching.
- The one left and one right row therefore contribute one pair.
x <- data.frame(id=NA_integer_,amount=5)
y <- data.frame(id=NA_integer_,name="unknown")
nrow(merge(x,y,by="id"))
Expected result: One joined row under default matching.
Why this result follows: Missing-key semantics need an explicit domain policy.
7. Reject unknown identifiers
Problem: Guard a lookup containing A and NA under a no-missing-key contract.
- The second key is missing and violates the declared contract.
- The stop prevents an unknown key from entering the lookup merge.
keys <- c("A",NA)
if (anyNA(keys)) stop("Missing lookup key")
Expected result: The guard stops before the join.
Why this result follows: An explicit precondition makes missing-key handling observable.
8. Compound-key uniqueness
Problem: Check whether customer and effective day uniquely identify A/1,A/2,B/1.
- The two A rows differ by effective day.
- The B row has a different customer even though its day is 1.
d <- data.frame(customer=c("A","A","B"),day=c(1,2,1))
anyDuplicated(d[c("customer","day")])
Expected result: 0: no duplicate compound key.
Why this result follows: The complete key determines uniqueness at the intended grain.
9. Explicit key beats implicit fields
Problem: Join equal IDs when the tables contain different shared status values.
- The explicit by argument restricts the join key to id.
- The differing status fields are output attributes rather than match requirements.
x <- data.frame(id=1,status="open")
y <- data.frame(id=1,status="closed")
nrow(merge(x,y,by="id"))
Expected result: One row matched on id=1.
Why this result follows: Naming the key protects the relationship from accidental shared columns.
10. Normalization collision
Problem: Inspect IDs A and A-space after trimming whitespace.
- Trimming removes the trailing space from the second ID.
- Both normalized strings then equal A.
ids <- c("A","A ")
normalized <- trimws(ids)
anyDuplicated(normalized)
Expected result: 2: the second normalized key duplicates the first.
Why this result follows: Normalization can merge identities and must be checked against the domain contract.
11. Match marker
Problem: Distinguish a matched missing region from an unmatched customer.
- The matched A row carries the explicit TRUE marker despite its missing region.
- B has no matching lookup row and receives a missing marker.
orders <- data.frame(id=c("A","B"))
lookup <- data.frame(id="A",region=NA_character_,present=TRUE)
merge(orders,lookup,by="id",all.x=TRUE)
Expected result: A has region=NA,present=TRUE; B has region=NA,present=NA.
Why this result follows: A nonmissing marker separates coverage from payload missingness.
12. Inflated order amount
Problem: Join one order worth 15 to three lookup rows sharing its key.
- The order matches all three lookup rows and is repeated three times.
- Adding the repeated amount gives 15+15+15=45.
orders <- data.frame(id="K",amount=15)
lookup <- data.frame(id=rep("K",3),tag=c("a","b","c"))
j <- merge(orders,lookup,by="id")
sum(j$amount)
Expected result: The joined sum is 45; source amount is 15.
Why this result follows: Summation at child grain multiplies a parent-grain amount.
13. Summarize line items
Problem: Aggregate order 7 lines 2,3,4 before attaching their total.
- The three lines share order key 7.
- Their amounts sum to 2+3+4=9.
lines <- data.frame(order=c(7,7,7),amount=c(2,3,4))
aggregate(list(total=lines$amount),list(order=lines$order),sum)
Expected result: One order 7 summary with total 9.
Why this result follows: One summary per order avoids line fanout when attached to an order table.
14. Two child tables
Problem: Find the number of line-tag pairs for one order with two lines and three tags.
- Each of the two line rows matches all three tag rows.
- The product 2Γ3 gives six rows at the combined grain.
lines <- data.frame(order=c(1,1),line=c("L1","L2"))
tags <- data.frame(order=rep(1,3),tag=c("a","b","c"))
nrow(merge(lines,tags,by="order"))
Expected result: Six line-tag pairs.
Why this result follows: Independent child relationships create a cross product within the parent key.
15. Offsetting total errors
Problem: Compare source amounts 10,10 with a result that duplicates the first and drops the second.
- The source includes one 10 for each of two IDs.
- The result includes two copies of a and none of b, retaining the same total.
source <- data.frame(id=c("a","b"),amount=c(10,10))
result <- source[c(1,1),]
c(source=sum(source$amount),result=sum(result$amount))
Expected result: Both totals are 20 despite missing b and duplicated a.
Why this result follows: Total conservation alone cannot detect offsetting identity errors.
16. Wrong association, same count
Problem: Compare two lookup mappings with the same keys and swapped regions.
- Both mappings contain two customer entries.
- Both region associations differ from their expected IDs.
expected <- c(A="north",B="south")
actual <- c(A="south",B="north")
c(count_same=length(expected)==length(actual),pairs_same=all(expected==actual))
Expected result: count_same=TRUE; pairs_same=FALSE.
Why this result follows: Checking known associations catches errors that row counts miss.
17. Empty lookup
Problem: Left-join two orders to an empty customer lookup.
- The right table contains no rows capable of matching either order.
- all.x retains each left order and fills its right fields with NA.
orders <- data.frame(id=c("A","B"),amount=c(2,3))
lookup <- data.frame(id=character(),region=character())
j <- merge(orders,lookup,by="id",all.x=TRUE)
c(rows=nrow(j),unmatched=sum(is.na(j$region)))
Expected result: Two rows remain and both have missing regions.
Why this result follows: Left retention and match coverage are distinct properties.
18. Restore source order
Problem: Restore source order B,A after a merge that may sort keys.
- The sequence column records original order independently of the key.
- Sorting the result by sequence places B before A.
orders <- data.frame(seq=c(1,2),id=c("B","A"))
lookup <- data.frame(id=c("A","B"),region=c("N","S"))
j <- merge(orders,lookup,by="id")
j[order(j$seq), , drop=FALSE]
Expected result: The restored IDs are B,A.
Why this result follows: An explicit order contract avoids reliance on merge row order.
19. Duplicate source ID
Problem: Detect repeated order ID 9 even when customer lookup keys are unique.
- The second order ID matches the first order ID.
- A unique customer lookup cannot repair a duplicated source entity ID.
orders <- data.frame(order_id=c(9,9,10),customer=c("A","B","C"))
anyDuplicated(orders$order_id)
Expected result: 2: order ID 9 repeats at the second row.
Why this result follows: Source-grain uniqueness is a separate precondition.
20. Guard a complete lookup
Problem: Validate unique keys and complete coverage for orders A,B and lookup A,B.
- The lookup has one row per key and covers both source keys.
- The merge contributes each amount once, so 4+6=10.
orders <- data.frame(id=c("A","B"),amount=c(4,6))
lookup <- data.frame(id=c("A","B"),region=c("N","S"))
stopifnot(!anyDuplicated(lookup$id),all(orders$id %in% lookup$id))
j <- merge(orders,lookup,by="id",all.x=TRUE)
c(rows=nrow(j),total=sum(j$amount))
Expected result: Two rows and total 10.
Why this result follows: The controls support the intended many-to-one complete lookup contract.
Common errors and fixes
A total increases after joining
- Why it happens
- A lookup key occurs more than once and duplicates matching rows.
- How to fix it
- Inspect key multiplicity and resolve the source or revise the relationship.
- Prevent it next time
- Assert the expected key uniqueness before the join.
An unmatched order disappears
- Why it happens
- The join type did not match the intended retention policy.
- How to fix it
- Choose the appropriate join and inspect unmatched keys.
- Prevent it next time
- Include an unmatched fixture and assert its expected outcome.
A row-count check misses an incorrect match
- Why it happens
- The same number of rows can still contain wrong associations.
- How to fix it
- Inspect keys and representative matched records as well as counts.
- Prevent it next time
- Test a wrong-key fixture with known expected matches.
20 practice exercises
1. How many rows result from the first fixture and why?
Show hint
Count matches for each order separately.
Show worked solution
Three rows result: order ID 1 matches two customer rows and order ID 2 matches one. A later sum would count the first amount twice unless the relationship is corrected.
Order ID 1 matches two customer rows and order ID 2 matches one, producing three joined rows. The order amount 10 is repeated, so a naive joined total is 10+10+20=40 instead of the source total 30.
Check your solution
- There are three joined rows.
- The naive joined total is 40 versus source total 30.
2. Why not silently keep the first duplicate customer?
Show hint
Ask what the duplicate represents before choosing a row.
Show worked solution
The duplicate may represent a data defect or a legitimate one-to-many relationship. Choosing the first row hides that decision and can discard information; resolve it according to the documented domain contract.
The two customer rows may be conflicting records or legitimate separate relationships. Keeping the first silently imposes an arbitrary choice and may discard the correct record; resolve the source or revise the key under a documented rule.
Check your solution
- The cause of the duplicate is investigated.
- The repair follows a documented relationship contract.
3. A unique lookup covers 93 of 100 unique orders. Predict left-join row count and matched/unmatched counts.
Show hint
A unique right key contributes at most one match per order.
Show worked solution
The left join preserves 100 order rows; 93 match and 7 are unmatched. Verify those counts and known associations before summing, since retention does not prove lookup completeness.
Check your solution
- Joined row count is 100.
- Matched and unmatched counts are 93 and 7.
4. A key has two left and three right rows, but the required output is one row per left row. What contract decision precedes the merge?
Show hint
The right multiplicity violates a many-to-one lookup.
Show worked solution
The equality merge would produce six pairs, not two left-grain rows. Resolve the right relationship or define a justified aggregation before joining; changing to a left join does not remove fanout.
Check your solution
- The naive key contributes six pairs.
- A right-side relationship decision is required.
5. Orders use customer A; a lookup has one A row and two duplicate B rows. Can the observed join avoid fanout while the lookup contract still fails?
Show hint
A duplicate key can be absent from the current source.
Show worked solution
Yes: A matches one row, so current orders do not fan out, but duplicate B violates a globally unique lookup contract. Repair or document the relationship before future B orders are processed.
Check your solution
- Current A orders have one match each.
- The lookup uniqueness contract fails for B.
6. A right-only customer must appear in a coverage report, while unmatched orders must also remain. Which merge option supports that report?
Show hint
Both sides need unmatched retention.
Show worked solution
Use all=TRUE for a full outer merge after stating the key. It retains unmatched rows from both tables; distinguish right-only customers from left-only orders with nonmissing markers.
Check your solution
- Both unmatched sides are retained.
- Markers distinguish their origin.
7. A lookup has one NA key and no duplicates. Why does anyDuplicated alone not enforce a no-missing-key policy?
Show hint
A single missing key need not be duplicated.
Show worked solution
anyDuplicated can return zero even though one NA is present. Test anyNA separately and reject or quarantine the missing key before merging under the stated contract.
Check your solution
- The duplicate check can pass.
- The missing-key check fails.
8. Customer A has rates for days 1 and 2. A transaction has day 2. Explain why joining on customer alone is wrong.
Show hint
The rate is identified by customer and day together.
Show worked solution
Joining on customer alone matches both rate rows and doubles the transaction. Join on the validated composite key (customer,day), which selects the day-2 rate only.
Check your solution
- The incomplete key produces two matches.
- The composite key selects day 2.
9. Two lookup tables have no common column names, and merge is called without by. What dangerous shape can result?
Show hint
An empty join key produces a Cartesian product.
Show worked solution
With two left and three right rows, an empty key produces six combinations rather than identity matches. Supply explicit by.x and by.y for the intended relationship and validate both columns.
Check your solution
- The unintended product has six rows.
- Explicit key mapping is required.
10. IDs Ab and ab are case-sensitive, but a proposed normalization lowercases both. What identity check is required?
Show hint
Normalization may collapse distinct entities.
Show worked solution
Both become ab after lowercasing, creating a collision. Reject this normalization under the case-sensitive contract or establish a documented domain rule before joining.
Check your solution
- The normalized keys collide.
- The case-sensitive contract is preserved.
11. A full join has left and right nonmissing row markers. Classify rows with (left,right) markers (TRUE,TRUE), (TRUE,NA), (NA,TRUE).
Show hint
Each marker identifies whether that side supplied a row.
Show worked solution
The first row is matched, the second is left-only and the third is right-only. Summarize all three coverage categories separately instead of inferring origin from optional payload values.
Check your solution
- The categories are matched, left-only, right-only.
- Each category has one row.
12. Two distinct orders each amount 10 match one row each. Why is sum(unique(amount)) an unsafe fanout repair?
Show hint
Equal amounts can belong to different entities.
Show worked solution
The correct source total is 20, but sum(unique(amount)) returns 10 and drops one legitimate order. Resolve duplicates by the order identity and relationship rather than distinct numeric values.
Check your solution
- The source total is 20.
- The distinct-value sum is 10.
13. A child aggregation receives one missing line amount. What policy and audit fields are needed before attaching its order total?
Show hint
Missing is not automatically zero.
Show worked solution
Specify whether the order total is unknown or computed from valid lines, and retain valid and missing line counts. Attach the summary only with a documented interpretation of its denominator and missingness.
Check your solution
- The missingness policy is stated.
- Valid and missing line counts are retained.
14. A line-tag report intentionally needs every combination. When is the six-row fanout correct, and which sum still needs care?
Show hint
Define output grain before declaring multiplication an error.
Show worked solution
For two lines and three tags, six combinations are correct if each pair is an intended record. An order-level header amount still repeats six times and cannot be summed as six orders.
Check your solution
- The pair grain has six rows.
- The header amount is not summed per pair.
15. Source orders a=3,b=7,c=10 become joined rows c=10,c=10. Explain why total reconciliation passes despite multiple identity defects.
Show hint
Two omitted amounts can equal one extra duplicated amount.
Show worked solution
Both totals are 20: the omitted a and b sum to 10, offsetting the extra copy of c. Check per-ID coverage and counts, which reveal two missing IDs and a duplicate.
Check your solution
- Both totals are 20.
- IDs a and b are missing and c repeats.
16. Source ID "001" is converted to integer 1 while lookup retains character IDs "001" and "1". Diagnose the identity risk.
Show hint
Leading zeros can distinguish domain identifiers.
Show worked solution
Numeric conversion collapses "001" and "1" to the same numeric value, so a later match can be ambiguous or wrong. Preserve character IDs and validate the lookup key vocabulary before joining.
Check your solution
- The raw IDs are distinct.
- Numeric conversion can collapse their identity.
17. The left table is empty and the right lookup has two unique customers. Compare left and full outer merge row counts.
Show hint
A left merge retains only rows from its empty left side.
Show worked solution
The left merge has zero rows because it retains left records and there are none. A full outer merge retains both right-only customers, producing two rows with missing left fields.
Check your solution
- The left result has zero rows.
- The full outer result has two rows.
18. One source row matches two child rows. How can a deterministic report order both the parent and its children?
Show hint
A parent sequence alone leaves a tie among child rows.
Show worked solution
Carry a stable source sequence and a child key, then order by both. The source sequence restores parent order and the child key resolves the two matches consistently.
Check your solution
- The parent sequence is retained.
- A child tie breaker is specified.
19. A source has repeated customer IDs but unique order IDs. Does repetition alone violate a many-to-one customer lookup?
Show hint
The entity grain differs between the source and lookup.
Show worked solution
No: several distinct orders may belong to the same customer. Require unique order IDs in the source and at most one row per customer key in the lookup; test each contract separately.
Check your solution
- Repeated customer IDs can be valid.
- Order and lookup keys are checked separately.
20. Customer A has rate intervals [1,5) and [4,8), with unique start keys. How many rates match an event on day 4?
Show hint
Evaluate both interval predicates, not just start-key uniqueness.
Show worked solution
Day 4 lies in both intervals, so two rates match even though the start keys 1 and 4 are distinct. Validate nonoverlapping effective intervals before a temporal lookup that requires one rate per event.
Check your solution
- The event has two matches.
- The intervals overlap on [4,5).
Key takeaways
- Check key multiplicity and retention before a join.
- Verify matches and amounts before computing summaries.
- A left merge retains unmatched rows but can multiply matches.
- Uniqueness and coverage are separate checks.
- A preserved grand total cannot establish correct associations.