55 min read

Customer Identity Resolution: How to Match Profiles in SQL

Build customer identity resolution checks with SQL examples. Compare exact matches, ambiguous records and consent boundaries for retail profiles.

Customer Identity Resolution: How to Match Profiles in SQL

Author: jackey.ye | Updated: 2026-11-27

Deterministic identity resolution in SQL links records only when they share an exact value in an identifier the business has decided to trust as person-unique. No identifier is inherently person-unique — that status is a governance decision backed by provenance, not a property of the field type. Nulls are excluded explicitly, ambiguous groups are quarantined rather than merged, and matching stays a data-linkage step separate from consent. This guide builds that pipeline on synthetic retail fixtures in PostgreSQL; every output quoted below is hand-derived from the fixture, not produced by a live database run.

What Is Deterministic Identity Resolution in SQL?

Deterministic matching assigns the same entity key only when records share an exact value in an identifier the business has verified as unique to one person. No similarity score, threshold or model sits between the input and the merge decision: every link traces back to one equality rule you can read in the query.

That "verified as unique" bar is an assumption the pipeline inherits, not something the SQL can prove. The queries below assume a registry in which loyalty IDs were issued one per person and checked at issue time. On real data you have to establish that assumption first — from how the identifier was issued, which source asserted it, and when — and record the evidence. If you can't, the rule is a guess wearing a WHERE clause.

That precision is worth separating from the neighbouring terms readers meet in vendor material. Rule-based matching uses configurable rules over specified fields, which may be exact or fuzzy; machine learning-based matching scores whole records and can detect more complex matches, including ones with variations or missing fields. Entity resolution is the broader discipline covering both. Master data management is the governance program that owns definitions and stewardship. A single customer view is a downstream presentation of resolved keys, not the matching logic itself.

The SQL in this article is a hand-built rule-based approach written from scratch. It is not a reproduction of any managed service, and it deliberately stops at exact equality — no fuzzy name or address comparison.

Why Is Identity Resolution Not Consent or Authorization?

Matching two records to one person is a data-linkage operation. It grants no permission to process, contact, profile or disclose that person's data.

Three questions get conflated in practice and must stay separate. Identity resolution asks "are these the same person?" Consent asks "may we process this data for this purpose?" Authorization asks "may this caller access this record?" The GDPR Article 4 definitions anchor the distinction: consent is a freely given, specific, informed and unambiguous indication of the data subject's wishes, while processing covers a wide set of operations including structuring, storage, retrieval, consultation, use and disclosure. Linking records is structuring and combining data, so it is itself processing that needs its own lawful basis — the merge does not inherit one. NIST's digital identity guidelines make the parallel point for access: authentication does not determine the claimant's authorizations or access privileges; that is a separate decision.

The engineering consequence is concrete. A resolved profile must still carry per-purpose consent flags, provenance of which source asserted each attribute, and access controls downstream. A pipeline that merges records collected under different consents silently widens data access, because the merged row now exposes attributes to every consumer that can read the entity key. For teams operating in Singapore and the United States, consent scope is jurisdiction- and purpose-specific, so store provenance and purpose alongside the key rather than assuming a merged profile is uniformly usable.

Which Identifiers Are Safe to Match On?

Match only on identifiers your data governance has classified as verified and person-unique. For the synthetic fixture, the loyalty IDs are assumed to come from a registry that issued exactly one per person; that assumption is stated, not demonstrated by the data. Never match on shared household contact details.

Four tests decide whether an identifier qualifies:

  • Uniqueness: can two people legitimately share this value? A household inbox fails; a loyalty number passes only if the registry enforces one per person.

  • Verification: was the value confirmed at capture, or merely typed once?

  • Stability: does it persist, or is it recycled — reassigned phone numbers being the classic case?

  • Provenance: which source asserted it, and when?

Two common assumptions deserve correction. A verified email proves the account holder can read that inbox — it does not prove one inbox maps to one person, which is exactly why the household case in the fixture exists. And a hash of a government ID is a pseudonym, not an anonymization: the input space is small and guessable, so a salted or unsalted hash of an ID number is still sensitive personal data and belongs under the same access controls as the raw value.

The household trap is worth spelling out. A family sharing one inbox collapses into a single profile under naive matching, corrupting order history, consent state and marketing suppression for everyone in that household.

Nulls must be excluded because SQL equality against NULL yields unknown, not true — ordinary comparison operators yield null when either input is null. A plain join therefore drops those rows silently. The null-safe alternative is worse for identity work: null-safe equality qualifies rows where both sides are NULL, which would match every missing identifier to every other missing identifier.

Case folding is a policy decision, not a default. Email local parts are technically case-sensitive even though most providers treat them case-insensitively. PostgreSQL's citext folds according to the database's LC_CTYPE setting and is, in its own documentation's words, not truly case-insensitive in Unicode terms; the docs recommend nondeterministic collations instead for Unicode special cases. Document the rule per identifier type and test it against your data.

How Do the Matching Approaches Compare?

Deterministic exact matching is auditable and cheap but misses variation; probabilistic matching catches variation but needs thresholds and review; managed services package both but add cost and vendor coupling. The table describes approaches generally — not any specific product's measured performance.

Dimension

Deterministic SQL matching

Probabilistic / ML matching

Managed entity-resolution service

Match basis

Exact equality on a verified identifier

Similarity score across several fields, merged above a threshold

Configurable rules, ML models, or third-party data providers

Typical inputs

Registry-issued loyalty ID, verified email, pseudonymous ID hash

Names, addresses, dates of birth, partial contact data

Whatever the service accepts, often including enrichment

Auditability

Every merge explainable by one rule in the query

Requires storing the score and the threshold version

Depends on provider logging and export

False-merge risk

Low when identifier policy is sound; rises with shared identifiers

Higher; threshold tuning trades false merges against misses

Varies by configuration and provider data quality

Review burden

Concentrated in quarantine review

Ongoing threshold and exception review

Shifts to vendor management plus your own exceptions

When to choose it

You have at least one identifier whose person-level uniqueness is verified and documented

Records vary in spelling and format and no clean key exists

You need provider enrichment or lack the team to build it

The rule-based versus ML-based distinction follows the matching workflow documentation, which also notes that rule-based output can feed a provider-based step to limit subscription cost. That composition pattern is worth copying regardless of vendor: run the cheap deterministic pass first, and send only unmatched records onward.

What Does the SQL Fixture Look Like?

The fixture is seven synthetic retail profile rows with deliberately planted edge cases: an exact duplicate, a case-variant email, a shared household email and phone, and a null identifier. Each row exists to exercise one rule. The loyalty IDs are treated as coming from a registry that issued one per person — an assumption for this fixture only.

Prerequisites and dialect: PostgreSQL 15 or later. The queries use standard SQL plus IS DISTINCT FROM and a VALUES list. In other dialects, null-safe comparison syntax differs (<=> in Databricks SQL, for example), and citext is PostgreSQL-specific. All expected outputs below were derived by hand from the fixture; run them yourself to confirm.

Example configuration — validate in your target environment.

CREATE TABLE raw_profiles (
      record_id      integer PRIMARY KEY,
      source_system  text    NOT NULL,
      full_name      text    NOT NULL,
      email          text,
      phone          text,
      loyalty_id     text,
      captured_at    date    NOT NULL
  );
  
  INSERT INTO raw_profiles VALUES
   (1,'pos','Mei Tan','mei.tan@example.com','+6591110001','LY-1001','2026-01-04'),
   (2,'web','M. Tan','MEI.TAN@example.com','+6591110001','LY-1001','2026-02-11'),
   (3,'crm','Daniel Lim','lim.family@example.com','+6592220002','LY-1002','2026-03-02'),
   (4,'web','Sarah Lim','lim.family@example.com','+6592220002','LY-1003','2026-03-19'),
   (5,'pos','Ahmad Rahman',NULL,NULL,'LY-1004','2026-04-07'),
   (6,'crm','Priya Nair','priya.nair@example.com','+6593330003','LY-1005','2026-05-23'),
   (7,'web','Priya N.','priya.nair@example.com','+6593330003','LY-1005','2026-06-01');
  

What each row tests, and the classification it must produce before you run any query:

record_id

Designed to test

Expected classification

1, 2

Exact duplicate plus a case-variant email on the same loyalty ID

Exact duplicate — safe to collapse to one entity

3, 4

Two different people sharing a household email and phone, with different loyalty IDs

Ambiguous — quarantine, never merge

5

Null email and phone; loyalty ID present

Clean singleton on loyalty ID; excluded from email/phone matching

6, 7

Same email and loyalty ID, different name spelling

Exact duplicate — name variation is irrelevant to the rule

Row 5 is the one that catches naive implementations: it has a usable loyalty identifier but nothing to match on email or phone, so it must appear in the exclusion count for those keys and still resolve cleanly on loyalty. Rows 3 and 4 are the harder case for the pipeline itself: because they carry different loyalty IDs, they look like two clean singletons to the loyalty grouping step, and only the separate quarantine pass keeps them out of the final key table.

How Do You Implement Deterministic Matching Step by Step?

Normalize under an explicit policy, exclude nulls with a visible count, group by the assumed-verified identifier, classify each group, quarantine the ambiguous ones — and only then assign entity keys, excluding every record that sits in an open quarantine. The order matters: if keys are assigned before quarantine, ambiguous records get keys and the quarantine becomes decoration.

  1. Stage and normalize. Apply one documented rule per identifier type: trim whitespace, fold email to lower case, keep phone digits with country code, and treat empty strings as null. Staging keeps the raw row intact so the normalization is auditable.

Example configuration — validate in your target environment.

CREATE TABLE stg_profiles AS
  SELECT
      record_id,
      source_system,
      full_name,
      NULLIF(lower(btrim(email)), '') AS email_norm,
      NULLIF(regexp_replace(phone, '[^0-9+]', '', 'g'), '') AS phone_norm,
      NULLIF(btrim(loyalty_id), '') AS loyalty_norm,
      captured_at
  FROM raw_profiles;
  

Expected output: 7 rows, with record 2's email folded to mei.tan@example.com and record 5's email and phone both null.

  1. Exclude null and empty identifiers with a counted exclusion. Filter explicitly rather than relying on join semantics, and log how many rows each key drops.

Example configuration — validate in your target environment.

CREATE TABLE matchable_profiles AS
  SELECT * FROM stg_profiles
  WHERE loyalty_norm IS NOT NULL;
  
  SELECT
      count(*) FILTER (WHERE loyalty_norm IS NULL) AS excluded_no_loyalty,
      count(*) FILTER (WHERE email_norm IS NULL)   AS excluded_no_email,
      count(*) FILTER (WHERE phone_norm IS NULL)   AS excluded_no_phone
  FROM stg_profiles;
  

Expected output: excluded_no_loyalty = 0, excluded_no_email = 1 (record 5), excluded_no_phone = 1 (record 5).

  1. Group by the assumed-verified loyalty identifier and count distinct source records.

Example configuration — validate in your target environment.

CREATE TABLE loyalty_groups AS
  SELECT
      loyalty_norm,
      count(*)                          AS record_count,
      count(DISTINCT source_system)     AS source_count,
      array_agg(record_id ORDER BY record_id) AS record_ids
  FROM matchable_profiles
  GROUP BY loyalty_norm;
  

Expected output: five groups — LY-1001 with 2 records, LY-1002 with 1, LY-1003 with 1, LY-1004 with 1, LY-1005 with 2.

  1. Classify each group. A singleton is clean; a multi-record group whose records agree on the verified identifier is an exact duplicate safe to collapse; a group whose records disagree on a person-unique attribute, or whose only shared key is a household contact, is ambiguous.

Example configuration — validate in your target environment.

CREATE TABLE group_classification AS
  SELECT
      g.loyalty_norm,
      g.record_ids,
      g.record_count,
      CASE
          WHEN g.record_count = 1 THEN 'singleton'
          WHEN count(DISTINCT p.email_norm) = 1 THEN 'exact_duplicate'
          ELSE 'ambiguous'
      END AS classification
  FROM loyalty_groups g
  JOIN matchable_profiles p USING (loyalty_norm)
  GROUP BY g.loyalty_norm, g.record_ids, g.record_count;
  

Expected output (hand-derived): LY-1001 and LY-1005 are exact_duplicate; LY-1002, LY-1003 and LY-1004 are singleton. Note that this step reports records 3 and 4 as clean singletons — the loyalty key alone cannot see the household collision.

  1. Quarantine ambiguous groups first. Write them to a durable table with a reason code, the conflicting record IDs and an open status, as shown in the next section. In this fixture the household pair is caught by a separate email-key check, because records 3 and 4 carry different loyalty IDs but one shared inbox. Do this before any key assignment.

  2. Assign a surrogate entity key to non-quarantined groups only, anti-joining against open quarantine rows so no group whose record IDs overlap a quarantine entry can receive a key.

Example configuration — validate in your target environment.

CREATE TABLE entity_keys AS
  SELECT
      c.loyalty_norm,
      md5('loyalty:' || c.loyalty_norm) AS entity_key,
      c.record_ids
  FROM group_classification c
  WHERE c.classification IN ('singleton', 'exact_duplicate')
    AND NOT EXISTS (
        SELECT 1
        FROM match_quarantine q
        WHERE q.status = 'open'
          AND q.record_ids && c.record_ids
    );
  

The && operator is PostgreSQL's array overlap test, so any record_id shared between an open quarantine row and a group blocks that group. Expected output (hand-derived): three rows — LY-1001, LY-1004 and LY-1005. LY-1002 and LY-1003 are suppressed even though they were classified singleton, because their record IDs ({3} and {4}) overlap the open quarantine entry {3,4}.

  1. Assert the exclusion. Don't trust the anti-join by inspection; prove it with two queries that must return the stated results.

Example configuration — validate in your target environment.

-- Expect: 0 rows (no keyed record overlaps an open quarantine entry)
  SELECT e.loyalty_norm, e.record_ids
  FROM entity_keys e
  JOIN match_quarantine q
    ON q.status = 'open' AND q.record_ids && e.record_ids;
  
  -- Expect: 0 rows (records 3 and 4 appear in no entity_keys row)
  SELECT k.entity_key, k.record_ids
  FROM entity_keys k
  WHERE 3 = ANY (k.record_ids) OR 4 = ANY (k.record_ids);
  

Expected output: both queries return zero rows. If either returns a row, the key assignment is wrong and the pipeline must fail the run rather than publish.

What the Key Is and Isn't

md5('loyalty:' || loyalty_norm) is a deterministic pseudonym, not an anonymous identifier. Three properties matter. It is collision-prone in principle: MD5 is broken as a cryptographic hash, so two distinct loyalty IDs could map to one key, and the correct production default is a keyed hash such as HMAC-SHA-256 or, better, a controlled surrogate mapping table that issues opaque sequential keys and stores the identifier-to-key link under access control. It is also unsalted here, so any value derived from a guessable identifier can be re-derived by anyone holding the same input — the prefix only namespaces it, it does not protect it. That prefix matters for another reason: without a source namespace (loyalty:, email:), the same string in two identifier spaces would collide.

How Do You Quarantine Ambiguous Matches for Review?

Quarantine is a durable table plus a review workflow, not a log line. Ambiguous groups get a reason code, the conflicting records and a state that blocks automatic merging until a human decides. Create it before entity_keys so the anti-join in step 6 has something to exclude against.

Example configuration — validate in your target environment.

CREATE TABLE match_quarantine (
      quarantine_id  bigserial PRIMARY KEY,
      match_key      text NOT NULL,
      key_type       text NOT NULL,
      reason_code    text NOT NULL,
      record_ids     integer[] NOT NULL,
      status         text NOT NULL DEFAULT 'open',
      detected_at    timestamptz NOT NULL DEFAULT now(),
      reviewed_by    text,
      reviewed_at    timestamptz,
      decision       text
  );
  
  INSERT INTO match_quarantine (match_key, key_type, reason_code, record_ids)
  SELECT
      email_norm,
      'email',
      'shared_contact_identifier',
      array_agg(record_id ORDER BY record_id)
  FROM matchable_profiles
  WHERE email_norm IS NOT NULL
  GROUP BY email_norm
  HAVING count(DISTINCT loyalty_norm) > 1;
  

Expected output (hand-derived): one row — match_key = lim.family@example.com, record_ids = {3,4}, status open. Because this insert runs before entity_keys, the anti-join clears LY-1002 and LY-1003 and stays in force until a reviewer sets decision and moves the row off open. That is the difference between quarantine as a gate and quarantine as a report.

Review load is the honest trade-off. Quarantine volume is a function of data quality and identifier policy: a rule that quarantines too aggressively stalls the pipeline behind a backlog, while one that quarantines too little lets false merges through and corrupts downstream history. Set a review SLA, record who decided what and when, and treat the decision as data. The pattern for tracing which run produced which decision is the same one described in SQL query audit trails with correlation IDs. Quarantine tables are also a form of failed-row handling, so teams already running layered pipelines can reuse the medallion quarantine and replay guidance for the replay side.

What Are the Engineering Limitations?

Deterministic SQL matching has no ground-truth labels, so you cannot compute true accuracy from the pipeline alone. It can report internal consistency and rule coverage — how many records matched, how many were excluded, how many are waiting on review — and nothing more.

The limits worth planning for:

  • Identifier drift. People change emails and phone numbers. Mitigation: carry validity windows on identifier-to-entity links so a match is time-bounded. Residual risk: historical orders may attach to an entity that no longer holds that identifier.

  • Recycling. A phone number can be reassigned to a new person. Mitigation: expire phone-based links after a policy period and re-verify on next capture. Residual risk: a fast reassignment inside the window still merges wrongly.

  • Household versus individual ambiguity. Mitigation: quarantine, as above. Residual risk: reviewer error, which is why decisions need an audit trail.

  • Quarantine review load. Mitigation: tune which identifiers trigger quarantine. Residual risk: any threshold is a judgment call, not a measurement.

  • Key derivation and quarantine ordering. A key derived from a broken hash can collide, and a key issued before quarantine makes the gate meaningless. Mitigation: route keys through a controlled surrogate mapping and anti-join open quarantine before assignment, with assertion queries in the run. Residual risk: a reviewer who closes a quarantine row without evidence, which the audit trail should surface.

  • Assumed uniqueness. The fixture assumes a loyalty registry that issues one ID per person; real registries drift. Mitigation: verify issue rules and provenance per source before treating an identifier as person-level. Residual risk: an unverified assumption silently merges distinct people.

  • Dialect differences. Null-safe comparison, array overlap and case-folding behavior vary by engine. Mitigation: pin the dialect and test the fixture in it.

Where a limitation is a governance problem rather than a SQL problem — consent scope, access control, retention — the fix belongs in the consent and authorization layer described earlier, not in a cleverer query.

How Should You Validate and Operate the Pipeline?

Validate against the stated fixture expectations on every change, then monitor exclusion counts, quarantine rate and merge reversals in production.

Acceptance checklist:

  1. Fixture outputs match the expected classifications for all seven records, treating record 5's loyalty ID as a legitimate singleton.

  2. The null-exclusion count is logged and non-zero where expected (record 5 on email and phone).

  3. Quarantine is populated before entity_keys, and entity_keys holds exactly three groups: LY-1001, LY-1004, LY-1005.

  4. The overlap assertion returns zero rows, and no entity_keys row contains record 3 or 4.

  5. The case-folding rule is documented per identifier type and covered by a test.

  6. The provenance evidence for treating the loyalty ID as person-unique is recorded, not assumed.

  7. The key is a documented pseudonym under a controlled mapping, not a bare md5 of a guessable value.

  8. Every merge is reversible through the audit trail.

  9. Consent flags and access controls are verified downstream of the resolved key.

Running these jobs on a platform with auditable run history — so each run's inputs, exclusions and quarantine inserts are traceable — makes the assertions above checkable after the fact; confirm dialect and feature support against your own environment before porting the queries. For layer ownership and reconciliation across bronze, silver and gold, the medallion implementation checklist is a useful companion.

Frequently Asked Questions

What is the difference between deterministic and probabilistic identity resolution?

Deterministic matching links records only when they share an exact value in an identifier the business has verified as person-unique, so every merge is explainable by one rule. That uniqueness is an assumption backed by provenance, not a property of the field. Probabilistic matching scores similarity across several fields and merges above a threshold, which catches variation but requires threshold tuning and review. This article implements only the deterministic approach.

Why must null identifiers be excluded from matching?

In SQL, comparing NULL with = yields unknown rather than true, so nulls are silently dropped from ordinary joins; null-safe operators such as IS NOT DISTINCT FROM would instead match every null to every other null. Both outcomes are wrong for identity work, so null and empty identifiers are filtered out explicitly and the exclusion count is logged.

Should email matching be case-insensitive?

It depends on your identifier policy. Email local parts are technically case-sensitive, though most providers treat them case-insensitively in practice. Case folding must be an explicit, documented rule per identifier type, and PostgreSQL's citext type folds according to database collation with known Unicode limitations, so test the rule against your actual data.

Why not merge records that share a household email or phone?

A shared inbox or mobile number can belong to several people, so merging on it collapses distinct individuals into one profile and corrupts order history, consent state and suppression lists. A verified email shows control of an inbox, not one-person uniqueness. Such groups are routed to quarantine for human review instead of being merged automatically.

Does identity resolution grant permission to use the data?

No. Identity resolution only determines whether records refer to the same person. Consent governs whether data may be processed for a given purpose, and authorization governs who may access it; both remain separate downstream controls that a resolved profile must still carry.

Related Articles