34. Reconcile a target table against its source

PySparkHardNULL trapDuplicate trap

reconciliation · data validation · full outer join · null-safe comparison · eqNullSafe

Open in Colab
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

A nightly job copies customers from the source system into the warehouse. The only check on it compares row counts, and the counts are close enough that nobody looks further.

Finance has found a customer whose credit limit in the warehouse is not the one in the source. You are asked for a proper reconciliation: every customer where the two tables disagree, and how.

Input tables

source_customers

One row per customer. customer_id is unique and never NULL.

target_customers

The loaded copy. customer_id is never NULL, but it is not guaranteed to be unique.

Both tables have the same columns:

Column Type Description
customer_id BIGINT The key.
email STRING Can be NULL.
city STRING Can be NULL.
credit_limit DECIMAL(10,2) Can be NULL.

Requirement

Return one row for every customer_id that has a problem. A customer with no problem does not appear. Check in this order and report the first that applies:

  1. MISSING_IN_TARGET: the id is in the source and not in the target.
  2. MISSING_IN_SOURCE: the id is in the target and not in the source.
  3. DUPLICATE_IN_TARGET: the id is in the source, and has more than one row in the target. The column values are not compared for these.
  4. MISMATCH: the id has one row on each side and at least one of email, city, credit_limit differs.

Comparing values:

  • Values are compared exactly. Pune and pune are different.
  • NULL on both sides is a match. NULL on one side and a value on the other is a difference.

mismatched_columns lists the columns that differ, separated by commas with no spaces, always in the order email, city, credit_limit. For example email,credit_limit. It is NULL for every issue other than MISMATCH.

Expected output

One row per customer with a problem.

Column Type Description
customer_id BIGINT
issue STRING One of the four values above.
mismatched_columns STRING Only for MISMATCH, otherwise NULL.

Explanation

Show explanationGives the answer away. Try the problem first.

The approach

A reconciliation has to answer three questions, and a row count answers none of them: is every key there, is every key there once, and do the values agree?

1. Count the target rows per key. A window count on the target marks the duplicated ids before anything is joined:

F.count("*").over(Window.partitionBy("customer_id")).alias("target_rows")

2. Full outer join on the key. A left join only sees what is missing from the target. An inner join sees neither side's missing rows. Only a full outer join keeps both. Each side brings a marker column (in_source, in_target) that is NULL when that side had no row.

3. Compare the columns with a null-safe comparison.

~F.col("s_email").eqNullSafe(F.col("t_email"))

eqNullSafe (<=> in SQL) returns true for NULL and NULL, and false for NULL and a value. It never returns NULL. With !=, both of those comparisons are NULL, and a NULL condition counts as "no difference".

4. Build the list of differing columns. concat_ws skips NULLs, so one when(differs, "name") per column, joined with commas, gives exactly the columns that differ, in a fixed order, and an empty string when none does.

5. Label in the order the statement gives, with one when chain, then distinct(): a duplicated customer has two joined rows that carry the same label.

The source has 150 rows and the target 152. The result has 35 rows: 6 missing in the target, 4 missing in the source, 4 duplicated, 21 mismatched.

Why the row counts were "close enough"

150 against 152 looks like two extra rows. What actually happened is 6 rows missing, 4 extra and 4 loaded twice: 150 − 6 + 4 + 4 = 152. Errors in opposite directions cancel. And a count says nothing at all about the 21 customers whose row is there with the wrong content.

Common wrong answers

Comparing with !=. 8 of the 21 mismatches have a value on one side and NULL on the other: an email that was lost, a credit limit that appeared from nowhere. != cannot see them. 5 mismatched customers are not reported at all, and 3 more are reported with an incomplete column list. These are usually the most interesting differences, because "value became NULL" is what a broken load looks like.

a != b OR a IS NULL OR b IS NULL. The usual first repair, and it overshoots. NULL on both sides is now reported as a difference. 28 customers who are fine are flagged, and the report has 49 mismatches instead of 21. A reconciliation that cries wolf gets ignored.

A left join from the source. Finds nothing that exists only in the target. 31 rows; the 4 MISSING_IN_SOURCE customers are gone. Rows in a target that are not in the source are often the serious ones: test data, or rows that were deleted upstream and never removed.

An inner join. 25 rows. Neither kind of missing row can appear.

No rule for duplicates. Two of the duplicated customers were loaded as exact copies. Both joined rows match the source, so they produce no issue and the duplication is invisible to a column comparison. The other two have a second copy with a different city, and are reported as a city mismatch, which sends whoever reads the report looking for the wrong problem. Check uniqueness of the key as its own step.

No distinct(). Each duplicated customer is reported twice. 39 rows.

Other ways to do it

IS DISTINCT FROM is the SQL-standard spelling of the null-safe "not equal", and gives the same result as NOT (a <=> b).

coalesce to a sentinel, as in coalesce(s.city, '') != coalesce(t.city, ''). This passes on this data. It breaks the day a real value equals the sentinel: an empty string that is a real value, a credit limit that really is 0 or −1. The null-safe operator has no such case.

exceptAll. source.exceptAll(target) returns 27 rows and target.exceptAll(source) returns 29. That is a fast and correct way to answer "do the tables differ?", and it handles NULLs and duplicates properly. It does not tell you which key is missing, which is duplicated, or which column differs. Use it as the alarm and the join as the diagnosis.

Row hashes. Comparing one hash per row is common on wide tables. Be careful how the hash input is built: concat_ws('|', 'a', NULL, 'b') and concat_ws('|', 'a', 'b', NULL) are the same string, a|b, because concat_ws skips NULLs. Two different rows get the same hash. Replace NULLs with a marker inside the hash input, or use a hash function that takes the columns separately.

Edge cases in the data

Case Where What it catches
Value on one side, NULL on the other 8 of the 21 mismatches !=.
NULL in the same column on both sides 28 customers with no issue "Different or either is NULL".
Ids only in the target 2001 to 2004 Left join, inner join.
Ids only in the source 6 customers Inner join.
Loaded twice, identical 2 customers Comparing columns without checking the key.
Loaded twice, second copy differs 2 customers Reporting a duplicate as a mismatch.
Two or three columns differ 6 customers The order and format of mismatched_columns.
Emails that differ only in case 2 customers Case-insensitive comparison.