Technical case study · Data correctness · dbt and pandas
How NULL handling breaks a data pipeline
A technical case study of nullable dbt merge keys, a pandas filter that retains missing values, and aggregation defaults that change pipeline results.
A pipeline can finish successfully and still produce the wrong data. A repeated load inserts duplicate rows. A filter keeps records with no identifiers. An aggregation silently drops the group with a missing key.
Each failure comes from treating missing values like ordinary values. The following technical reproductions show why the results differ and how to repair them. They are examples, with no measured client outcomes claimed.
1. A nullable dbt unique_key creates duplicates
Consider an incremental model whose grain is one row per account and external reference:
{{ config(
materialized='incremental',
incremental_strategy='merge',
unique_key=['account_id', 'external_reference']
) }}
Suppose the target already contains (42, NULL), and a later batch contains an update for that same logical record. With an equality-based merge, the relevant match condition is:
target.account_id = source.account_id
AND target.external_reference = source.external_reference
The first comparison is true. The second is unknown (NULL). Together, they do not produce true, so the row does not match. The merge can insert another (42, NULL) instead of updating the existing row. Replaying the batch can repeat the problem.
One non-null component is not enough. Every equality in the composite match must succeed. dbt explicitly warns that nullable components of unique_key can prevent matching and produce duplicates. The exact behavior depends on the adapter and incremental strategy; inspect the generated SQL. See dbt’s incremental model documentation.
The comparison behind the failure
This BigQuery query makes the distinction visible:
SELECT
CAST(NULL AS STRING) = CAST(NULL AS STRING) AS null_equals_null,
CAST(NULL AS BOOL) = TRUE AS null_equals_true,
NULL AND TRUE AS null_and_true,
NULL AND TRUE AND FALSE AS null_and_false,
CAST(NULL AS STRING) IS NOT DISTINCT FROM
CAST(NULL AS STRING) AS null_safe_equal;
| Expression | Result |
|---|---|
NULL = NULL | NULL |
NULL = TRUE | NULL |
NULL AND TRUE | NULL |
NULL AND TRUE AND FALSE | FALSE |
NULL IS NOT DISTINCT FROM NULL | TRUE |
These results follow BigQuery’s comparison and logical operators. A join or merge condition needs true to match. Unknown is not true. A null-safe comparison can express the desired matching behavior, but changing a model’s SELECT does not automatically change dbt’s generated merge predicate.
Make the identity rule explicit
If a key component must always exist, reject or quarantine records where it is missing. If missing values are legitimate parts of the identity, a surrogate key can provide a stable, non-null value for matching:
{{ config(
materialized='incremental',
incremental_strategy='merge',
unique_key='record_key'
) }}
SELECT
{{ dbt_utils.generate_surrogate_key([
'account_id',
'external_reference'
]) }} AS record_key,
account_id,
external_reference,
amount
FROM {{ ref('stg_records') }}
This illustrative model reads all staging rows so the matching behavior is easy to inspect. Add the production incremental filter separately, with an explicit policy for late updates.
The dbt-utils implementation casts components, substitutes a marker for nulls, joins them, and hashes the result. By default it distinguishes null from an empty string; the legacy surrogate_key_treat_nulls_as_empty_strings setting changes that behavior.
For string fields, the underlying idea can also be demonstrated directly:
CONCAT(
COALESCE(field_1, '<NULL>'), '|',
COALESCE(field_2, '<NULL>'), '|',
COALESCE(field_3, '<NULL>')
) AS record_key
This is safe only with a defined encoding: a real '<NULL>' value must not collide with the null marker, and delimiters in values must not make different tuples serialize identically. For example, ('a|b', 'c') and ('a', 'b|c') produce the same joined text. Hashing an ambiguous encoding does not remove that ambiguity; generated keys still need validation against the actual data domain.
A surrogate key also cannot invent identity. If two separate records have identical components, including an all-null tuple, they receive the same key. If a component changes from null to a known value, the key changes too: decide whether that represents a new row or requires reconciliation through a stable identifier.
Verify the repair, including existing data
Add not_null and unique tests to the generated key, and check the incoming batch before merging:
version: 2
models:
- name: fct_records
columns:
- name: record_key
data_tests:
- not_null
- unique
Replay an identical batch twice and confirm that row counts and totals stay unchanged. Include partially null keys, all-null keys, empty strings, delimiter characters, and null-to-known updates in the fixture.
Changing the key logic does not remove duplicates already stored in the target. Rebuild or deduplicate affected data using a documented winner rule, populate the new key for historical rows, and reconcile downstream totals before resuming normal loads.
2. A pandas filter keeps records with no identifiers
The same assumption can break a Python filter intended to keep non-empty identifier lists. Here is a reproduction with a populated list, an empty list, None, and NaN:
import pandas as pd
records = pd.DataFrame({
'identifier_value': ['has_figi', 'empty_list', 'none_val', 'nan_val'],
'figis': [['BBG000BLNNV0'], [], None, float('nan')],
})
is_empty = records['figis'].str.len() == 0
incorrect = records.loc[~is_empty]
For this object-typed column, .str.len() produces 1, 0, NaN, and NaN. Comparing NaN == 0 gives false. Inverting the mask therefore keeps both missing values alongside the non-empty list.
| Input | Length | Old filter keeps it | Corrected filter keeps it |
|---|---|---|---|
| One-element list | 1 | Yes | Yes |
| Empty list | 0 | No | No |
None | NaN | Yes | No |
NaN | NaN | Yes | No |
If the business rule is “missing means no usable identifiers,” normalize the missing length before comparing:
lengths = records['figis'].str.len().fillna(0)
nonempty = records.loc[lengths > 0]
assert nonempty['identifier_value'].tolist() == ['has_figi']
You could also repair the original mask with ~(lengths == 0). Using lengths > 0 states directly which rows to keep.
This policy assumes the column contains lists or missing values. Validate that contract separately: strings also have lengths. If missing means “lookup failed” or “not fetched yet,” keep that state distinct from a successful lookup returning an empty list. Otherwise the fix can hide records that should be retried.
Do not generalize the observed NaN comparison to every pandas dtype: nullable extension types can propagate pd.NA through comparisons. Make the missing-value policy explicit before filtering.
3. Grouping NULLs is different from comparing NULLs
SQL grouping does not use the same rule as an equality predicate. BigQuery and Spark SQL put rows with a null grouping key into one group. Spark documents this distinction in its NULL semantics reference.
Here is a BigQuery example:
WITH events AS (
SELECT 'A' AS account_id, 10 AS amount
UNION ALL SELECT CAST(NULL AS STRING), 20
UNION ALL SELECT CAST(NULL AS STRING), 30
UNION ALL SELECT 'B', CAST(NULL AS INT64)
)
SELECT account_id, COUNT(*) AS rows_in_group, SUM(amount) AS total
FROM events
GROUP BY account_id;
The result, without a guaranteed row order, is:
| account_id | rows_in_group | total |
|---|---|---|
| A | 1 | 10 |
| NULL | 2 | 50 |
| B | 1 | NULL |
COUNT(*) counts rows, including rows with missing values. COUNT(amount) would return zero for B. SUM(amount) ignores null inputs but returns null when every input is null. See BigQuery aggregate functions.
Where a SQL-to-pandas pipeline changes the result
For the same data, pandas 2.2 defaults differ in two important ways:
| Operation | BigQuery / Spark SQL | pandas 2.2 default |
|---|---|---|
| Group by a missing key | Retains a null group | Drops the missing-key group |
| Sum an all-missing group | Returns NULL | Returns zero with min_count=0 |
In pandas, groupby(dropna=False) retains missing keys. Use sum(min_count=1) to preserve an all-missing sum as missing:
events = pd.DataFrame({
'account_id': ['A', None, None, 'B'],
'amount': [10, 20, 30, None],
})
totals = events.groupby('account_id', dropna=False)['amount'].sum(min_count=1)
Check these defaults when upgrading pandas; specify the intended behavior explicitly. This retains the missing-key group with total 50 and leaves B’s total missing. The distinction matters: no observed amount and an observed amount of zero answer different business questions.
Define missing values at each boundary
Before changing a merge key, filter, or aggregation, define what missing means at that boundary. Then verify three properties:
- Identity: repeated input updates the same logical row, even when optional attributes are missing.
- Eligibility: filters distinguish usable data, empty results, and failed or incomplete enrichment.
- Reconciliation: grouping preserves the intended population, and missing totals remain distinguishable from zero.
A successful job status alone cannot tell you whether these rules hold. Discuss a data platform audit if your team is tracing duplicate records or totals that drift between pipeline stages.