Skip to content

Privacy and preparation

Dataset referential integrity audit: finding broken IDs and orphans

By SourceX Editorial · Updated

10 sections

Short answer

Detect broken identifiers by listing every relationship in the archive as a child key pointing to a parent key, then testing each one: parent keys unique and present, child keys never silently null, every child matched to a parent and every unexpected childless parent explained. Classify each orphan by cause, such as deletion, merge, export scope or format drift, and ship the counts in an integrity report with the delivery.

Checklist

Dataset referential

This page covers dataset referential integrity audit: finding broken IDs and orphans.Illustrative

Key takeaways

  • Files that open and parse can still hold thousands of tickets, lines or comments that point to nothing.
  • Standard foreign key tests skip null values, so a link cleared by a deletion passes unless you test for it separately.
  • Merges, retention deletions and export date windows are the usual causes of orphans, and each has a different fix.
  • An orphan record report lists every relationship, its counts, the cause of each break and what was repaired or disclosed.
  • Declare the keys in the dataset metadata so the buyer's loader can check the same joins on arrival.

How do you detect broken identifiers that disconnect an operational archive?

Write down every relationship the archive depends on, then test each one in both directions with joins rather than by opening files. PostgreSQL's documentation describes a foreign key as a rule that values in one column must match values in some row of another table, and calls the result referential integrity. An export from a help desk, CRM or ERP usually arrives as separate files with no such rule enforced, so the audit has to recreate it.

The basic test is an anti-join: list child rows whose parent key has no match in the parent table. Run it for every relationship, then reverse it to find parents with no children where children are expected, such as orders with no lines. Count both, sample both, and find the cause before deciding anything.

The output is not a pass or fail flag. It is a report that a buyer's acceptance owner can read: which relationships were tested, how many rows broke, why, and what the supplier did about it.

Why does an archive that opens cleanly still fail acceptance?

Because the defects that matter are between files, not inside them. A comment table can parse perfectly and still contain comments on tickets that are not in the ticket table, or attachments whose stored file never made it into the export. A model trained on the joined data loses the conversation history it was bought for.

Source systems also break links by design. Salesforce documents that deleting a master record also deletes its detail records, so a master-detail history can vanish without leaving a single orphan to detect. For an optional lookup, the default when the related record is deleted is to clear the field, which leaves a null where a link used to be.

Merges change identifiers. HubSpot's help center says that merging records creates a new Record ID by default, with the original IDs kept in a Merged IDs property, and that merged records cannot be unmerged; accounts in a public beta keep the primary record's ID instead. An export that includes activity rows written before a merge can point at IDs that no longer exist as records unless the merged ID property is used to resolve them.

Which relationships must be mapped before any test runs?

Build a relationship register first: one row per link, naming the child key, the parent key, the expected cardinality and whether a missing parent is ever legitimate. The register below is illustrative for a support and CRM archive; a real one comes from the source system's data model and the people who administer it.

Which relationships must be mapped before any test runs?
RelationshipChild key to parent keyExpected cardinalityMissing parent allowed?
Ticket to requestertickets.requester_id to users.idMany tickets per userNo; deleted users need a stub or pseudonymous key
Comment to ticketcomments.ticket_id to tickets.idOne or more comments per ticketNo
Attachment to commentattachments.comment_id to comments.id, plus file path to stored fileZero or more per commentNo; a missing file is its own defect
Ticket to accounttickets.account_id to accounts.idMany tickets per accountYes when the requester had no account
Contact to accountcontacts.account_id to accounts.idMany contacts per accountYes for unaffiliated contacts
Order line to orderorder_lines.order_id to orders.idOne or more lines per orderNo
Invoice to orderinvoices.order_id to orders.idZero or more invoices per orderOnly for invoices raised without an order, if that is policy

Ten checks cover most archives, and the most important are the ones ordinary tests skip. dbt's relationships test, for example, validates that child records have a matching parent but excludes null values by default, consistent with how database foreign keys behave; PostgreSQL likewise lets a referencing row escape the constraint if any of its referencing columns is null, unless the key is declared MATCH FULL. A link cleared by a deletion therefore passes both unless you add a separate not-null or null-rate check.

At a glance

Which checks find orphans, cleared links and silent breaks

When loading the export into a staging database, PostgreSQL can add a foreign key as NOT VALID, which skips the scan of existing rows while still checking new ones, and then validate it later. That is handy for loading first and auditing second, as long as nobody mistakes an unvalidated constraint for a clean result.

  • Parent key health: every parent key is unique and non-null.
  • Child to parent: anti-join each relationship and count unmatched child rows.
  • Parent to child: count parents with no children where the register says children are expected.
  • Null and cleared references: null rate per foreign key, compared with the rate the source system should produce.
  • Composite keys: rows where some key columns are null and others are not.
  • Format drift: the same ID stored with different case, padding, leading zeros or type in two files.
  • Merged and remapped IDs: child keys that match only an old ID listed in a merge or migration map.
  • File references: every attachment path resolves to a file, and the file's size and checksum match the manifest.
  • Time order: no child created before its parent, allowing for documented clock differences.
  • Cross-batch drift: keys that appear in one export batch but not the batch that should hold their parent.

What should the referential integrity and orphan record report include?

Ten parts, each short enough to read in a minute and specific enough for a buyer to accept or reject on. The example entries are illustrative.

What should the referential integrity and orphan record report include?
Report partContentsIllustrative entrySigned off by
Scope reconciliationRow counts per table against the source system for the same scope and datesTickets: export count equals source count for the licensed periodSupplier data owner
Relationship registerEvery tested link with cardinality and missing-parent ruleSeven relationships, two allow missing parentsData engineer
Key healthDuplicate and null parent keys per tableNo duplicate user IDs; no null ticket IDsData engineer
Orphan countsUnmatched children per relationship, as count and percentageComment to ticket: 0.4 percent unmatchedData engineer
Orphan causesEach orphan group assigned a cause from the cause tableMost comment orphans trace to tickets deleted under retentionData engineer with system admin
Cleared referencesNull rates per foreign key against expected ratesTicket to account nulls higher after a known cleanupSystem admin
ID resolutionMerged or migrated IDs resolved through a map, and how many remain unresolvedMerge map resolves most activity rows on merged contactsData engineer
Attachment integrityMissing, empty or checksum-mismatched filesTwelve attachments missing from storageData engineer
Exception logEvery repair, exclusion and stub, with reason and row countsOrphaned comments excluded; stubs added for deleted usersSupplier data owner
Verdict and limitsWhat the buyer can and cannot join, and known residual breaksAll required joins usable; attachment gaps disclosedSupplier data owner and buyer acceptance owner

How should orphans be classified by cause, and which fix matches each?

Every orphan group needs a cause before a fix, because the same count can call for repair, exclusion or nothing at all. The table pairs common causes with how they show up and what to do.

How should orphans be classified by cause, and which fix matches each?
CauseHow it shows upFixWhat to disclose
Retention or manual deletion of parentsChildren whose parent IDs fall in a deleted range or periodExclude children, or add stub parents if the content still has valueCount excluded or stubbed, and why
Cascade deletion at sourceNo orphans, but gaps in history around deleted parentsNothing recoverable; compare counts with older backups if allowedKnown gap and its period
Lookup cleared on deleteNulls where a link is required by the business processRecover from audit history if the source keeps oneNull rate before and after recovery
Record mergesChild keys matching old IDs from a merge propertyRemap through the merge mapCount remapped and unresolved
Export scope cutChildren inside the date window whose parents were created earlierWiden the parent extract to all referenced parentsNone if fixed; otherwise count
Format drift between systemsMatches appear after normalizing case, padding or typeNormalize keys in one documented stepThe normalization rule
De-identification dropped a parent tableAll children of a removed table become orphansReplace direct identifiers with consistent pseudonymous keys instead of dropping rowsWhich keys are pseudonymous

Worked example: a help desk and CRM export for a support model

This example is illustrative. A company exports three years of tickets, comments and attachments from its help desk and accounts and contacts from its CRM, for a buyer training a support agent. Every file parses, and row counts match the source for the licensed period.

The audit finds that roughly 3 percent of comments point to tickets that are not in the export. Sampling shows two causes: tickets created before the export window with comments inside it, and tickets deleted under a retention rule. The first group is fixed by widening the ticket extract to every referenced ticket; the second is excluded and counted. About 6 percent of tickets carry a null account where the business process requires one, and the CRM's field history shows a cleanup that cleared them, so most are recovered from history. A merge map resolves contact IDs on older activity rows. Twelve attachments are missing from storage and are listed by ID.

The report states each count, cause and action, and the verdict says the ticket to comment and ticket to requester joins are complete for the delivered scope.

The exception is a deliberate orphan. The company licenses tickets but withholds accounts for a business unit outside the agreed scope. Those tickets point to accounts that will never be delivered. They are not defects; the report lists them as out-of-scope references, and the account key is replaced by a consistent pseudonymous key so the buyer can still group tickets by account without seeing it.

How should keys be declared so a buyer can rejoin the tables?

Put the relationships in machine-readable metadata, not only in the report. The Croissant metadata format lets a field reference a field in another record set, which its specification describes as the equivalent of a foreign key, so record sets can be joined. Frictionless Table Schema has a foreignKeys property, modelled directly on SQL foreign keys, that connects fields in one resource to fields in the same or another resource.

Declaring keys this way lets the buyer's loader run the same joins on arrival and compare its counts with the report. It also makes the next delivery cheaper: the register, the checks and the declared keys carry over, and only the counts change.

Repair at source when the cause is a scope cut or a format rule you control; re-export when repairs would otherwise be hand edits; disclose when the break is permanent. Hand-editing an export to hide orphans creates a dataset nobody can reproduce, which a buyer's acceptance owner will rightly distrust.

  • Stop and re-scope when a required relationship breaks for a large share of rows and the cause is unknown.
  • Re-export when more than one cause needs a code change; keep the old export and its report for comparison.
  • Bring in the system administrator when nulls or gaps line up with a cleanup, migration or merge campaign.
  • Bring in a privacy reviewer before adding stub parents or pseudonymous keys for deleted people.
  • Disclose permanent gaps with their period and counts rather than dropping the affected children silently.

How does a clean integrity report help when an archive is licensed?

A clean integrity report is part of what makes an operational archive usable to an AI developer, alongside rights and privacy review. SourceX takes a company from rights review and contracting through data preparation and delivery when it licenses selected business records for AI.

Eligibility is checked through a brief questionnaire about the company, with no export required, and nothing is delivered until the company has approved the scope and terms and signed, so an audit like this one can shape what is offered.

Frequently asked questions

What is an orphan record?

An orphan record is a row whose reference to a parent record points to nothing, such as a comment whose ticket ID is not in the ticket table. In a delivered dataset it usually means context the buyer expected to join is missing.

Why don't foreign key tests catch every broken link?

Most foreign key checks skip null values, so a link that a source system cleared on deletion passes. dbt's relationships test excludes nulls by default, and PostgreSQL lets a row with a null key escape the constraint, so null rates need their own check.

Should orphan records be deleted before delivery?

Not automatically. First find the cause: some orphans are fixed by widening the export, some by remapping merged IDs, and some are legitimate out-of-scope references. Exclude only what cannot be repaired, and record the count and reason.

How do record merges affect a dataset export?

Merges can replace record IDs, so activity written before the merge may point to IDs that no longer exist as records. HubSpot, for example, creates a new Record ID on merge by default and keeps the old IDs in a Merged IDs property, which can be used as a remapping table.

Who should sign off the integrity report?

The data engineer who ran the checks, the system administrator who can explain deletions and merges, and the supplier's data owner for scope and exceptions. The buyer's acceptance owner reviews it against their own join checks on arrival.

Sources

  • PostgreSQL defines a foreign key as values that must match a row in another table, maintaining referential integrity, and lets rows with null referencing columns escape the constraint unless MATCH FULL is used. Source
  • PostgreSQL can add a foreign key as NOT VALID, skipping the scan of existing rows until VALIDATE CONSTRAINT runs. Source
  • dbt's relationships test checks that child records have a parent and excludes null values by default. Source
  • In Salesforce, deleting a master record deletes its detail records, and the default for an optional lookup is to clear the field. Source
  • HubSpot creates a new Record ID on merge by default, keeps original IDs in a Merged IDs property and does not allow unmerging. Source
  • Croissant lets a field reference a field in another RecordSet, the equivalent of a foreign key, so record sets can be joined. Source
  • Frictionless Table Schema foreignKeys connect fields across resources and are modelled on SQL foreign keys. Source

See if your company qualifies

A short company assessment. No data uploads are needed.

See if your company qualifies