Sub topic 12
Preserving relationships and planning restore order
This chapter assumes you can write basic SOQL, run sf data query, and read a CSV. It also assumes you know what a lookup and a master-detail field are. The chapter explains how to keep relationships intact in an export and how to decide the order in which objects are loaded back.
Why relationships decide whether a backup is usable
A Salesforce record points to other records through relationship fields. A Contact stores the Id of its Account in AccountId. An Opportunity stores AccountId and OwnerId. A Task stores WhatId and WhoId.
A CSV export keeps those values as plain text. The backup is only useful if, at restore time, each stored Id can be matched to a record that exists in the target org. Two facts make this harder than it looks:
- Record Ids are generated by the org. If you insert a record into an org, it receives a new Id, even if the CSV row contained the old one.
- A child row cannot be inserted until its parent exists, when the relationship field is required or the parent is validated.
So a restore must do two jobs: load parents before children, and translate old Ids into new ones.
Relationship types and what they require
| Relationship | Parent required? | Effect on restore |
|---|---|---|
| Master-detail | Yes, always | The parent must be loaded first. The child inherits sharing and is deleted with the parent. |
| Lookup (required) | Yes, when the field is marked required | The parent must be loaded first. |
| Lookup (optional) | No | The child can load first, and the lookup can be filled in later by an update. |
| Polymorphic lookup (`WhatId`, `WhoId`, `OwnerId`) | Depends | The target can be one of several objects, so the export needs to record which object each Id belongs to. |
| Self-lookup (`Account.ParentId`) | No | Rows in the same file depend on each other. Load in two passes. |
Exporting parent fields and child records
SOQL can follow a relationship in two directions. Going from child to parent uses dot notation and returns a flat column:
SELECT Id, FirstName, LastName, AccountId, Account.Name
FROM ContactGoing from parent to child uses a subquery. The result is nested, so flat CSV tools cannot write it:
SELECT Id, Name,
(SELECT Id, LastName FROM Contacts)
FROM Account
LIMIT 100For backups, avoid subqueries. Export every object with its own flat query and keep the foreign key column (AccountId) in the Contact file. The parent-child link is then preserved by the Id values in the child file. The Account.Name column is a convenience for humans. It is not what the restore depends on.
Always select the relationship Id fields explicitly. A query that selects only Account.Name and omits AccountId loses the link.
Keep the old Id as an external reference
Because inserted records get new Ids, you need a way to map old to new. There are two common approaches.
- External Id field. Create a custom field such as
Legacy_Id__con each object and mark it as an External Id. During a restore, populate it with the old Id. Child rows can then reference the parent by that field instead of by the new Id, and an upsert can match on it. - Mapping files. After loading a parent object, export the new Ids together with the old ones, and use that file to rewrite the foreign keys in the child CSV before loading it.
The external Id approach is simpler to repeat and is safer if a load is interrupted halfway, because an upsert on Legacy_Id__c does not create duplicates when you rerun it. It does require that the field exists in the target org before the restore. That field is part of your metadata backup, so restore metadata first.
A restore of a Contact that references its Account by external Id looks like this in a Data Loader mapping, shown here as the CSV column names:
Legacy_Id__c,LastName,Account:Legacy_Id__c
003xx0000001AAA,Rivera,001xx0000001AAA
003xx0000001AAB,Okafor,001xx0000001AABThe column Account:Legacy_Id__c tells the loader to find the Account whose Legacy_Id__c equals that value, then fill in AccountId. This works only if the Accounts were loaded first and their Legacy_Id__c was set.
Planning restore order
Build the order from the dependencies. Start with objects that depend on nothing, and move outward. Lay out the dependencies as a graph, then load in layers.
A workable order for a standard sales org is:
- Metadata: custom objects, fields (including
Legacy_Id__c), record types, and validation rules in a state that allows the load. - Users, roles, and profiles. Many records have an
OwnerId, so users must exist first. - Accounts, loaded in two passes if you use
ParentId. - Contacts, then Opportunities.
- Products, price book entries, then Opportunity line items.
- Activities (Tasks, Events), Notes, and Attachments, which point to many parent types.
Check this against your own org. Custom objects with master-detail fields add their own layers, and the actual order must come from the field definitions, not from this example.
Self-referencing and circular dependencies
Account hierarchy is the usual case. Account A has parent B, and B has parent C. If you load all Accounts in one pass, some rows reference parents that do not exist yet.
The usual solution is two passes. First insert all Accounts with ParentId blank, populating Legacy_Id__c. Then run an update that fills ParentId using the external Id reference. The same approach handles two objects that point at each other through optional lookups.
Things that quietly break a restore
- Triggers, flows, and validation rules. Loading historical data can fire automation, send emails, or fail validation. Plan to deactivate or bypass these during the load and reactivate them afterward.
- System fields.
CreatedDate,CreatedById, andLastModifiedDateare set by the system on insert. Writing original values needs the "Set Audit Fields upon Record Creation" permission, which you must enable on purpose. - Inactive owners. An
OwnerIdthat points to a deactivated user may be rejected. Decide on a fallback owner. - Record types and picklists. A value that no longer exists as an active picklist value can fail on insert.
- Read-only and formula fields. Exclude formula, auto-number, and other calculated fields from load files. They appear in an export but cannot be written.
- Polymorphic Ids. The first three characters of a Salesforce Id identify the object type (for example
001for Account and003for Contact). You can use this prefix to split aWhatIdcolumn by target object.
Checking that links survive in the export
Before you rely on a backup, test that the foreign keys resolve inside the files themselves. Export the Account Ids and the Contact AccountId values, then look for Contacts whose parent is missing:
#!/usr/bin/env bash
set -euo pipefail
ORG="my-prod-alias"
sf data query \
--query "SELECT Id FROM Account" \
--result-format csv \
--target-org "$ORG" > accounts.csv
sf data query \
--query "SELECT Id, AccountId FROM Contact WHERE AccountId != null" \
--result-format csv \
--target-org "$ORG" > contacts.csv
# Parent Ids, without the header row, sorted
tail -n +2 accounts.csv | sort > account_ids.txt
# Contact AccountId values, without the header row, sorted and unique
tail -n +2 contacts.csv | cut -d, -f2 | sort -u > contact_parent_ids.txt
# Ids that appear in contacts.csv but not in accounts.csv
comm -13 account_ids.txt contact_parent_ids.txtThe script prints nothing when every Contact points to an exported Account. Output means an orphan reference. This check is simple and assumes no commas inside the Id columns, which holds for Salesforce Ids. Orphans can appear if the two queries ran at different times and an Account was deleted in between, or if a filter excluded some parents.
Decide the restore scope up front
Not every restore is a full rebuild. Write down which of these you are preparing for, because the order and Id handling differ:
- Restoring a few deleted or damaged records into the same org. Original parents usually still exist, so the old Ids in the CSV remain valid and no mapping is needed.
- Restoring into a sandbox for analysis. Ids will be new, so you need the external Id or mapping approach.
- Rebuilding an empty org. You need the whole sequence: metadata, users, then data in dependency order.
Summary
Relationships are stored as Ids, and Ids change on insert. To keep a backup restorable, export each object flat with its foreign key columns, store the original Id in an external Id field on restore, and load objects in dependency order, parents first. Handle self-references with a second update pass, switch off automation during the load, and test that foreign keys resolve in your files before you need them.
Exercise
Your Contact export contains an AccountId column. You restore Accounts into a new sandbox, and every Account receives a new Id. How can you load the Contacts so that each one still links to the correct Account, and what must exist before you start?
Show answer
Use an external Id. Before the restore, create a Legacy_Id__c field marked as an External Id on Account (this comes from the metadata restore). Load the Accounts first and populate Legacy_Id__c with the original Id from the export. Then load Contacts with a column such as Account:Legacy_Id__c holding the old AccountId value, so the loader looks up the new parent. An alternative is to export the new Account Ids with their old Ids and rewrite the AccountId column in the Contact file before loading.
Exercise
Account has a self-lookup field ParentId. Why can a single-pass load of all Accounts fail, and how do you avoid the failure?
Show answer
Some rows reference parent Accounts that have not been inserted yet, so the lookup cannot be resolved. Load in two passes. First insert all Accounts with ParentId blank and with Legacy_Id__c populated. Then run an update that sets ParentId by referencing the parent through its external Id.
Exercise
The link check script prints three Ids. What do they mean, and what are two likely causes?
Show answer
They are Account Ids that appear in the Contact file's AccountId column but not in the Account file, so those Contacts are orphans. Likely causes are that an Account was deleted between the two queries, or that the Account query was filtered or limited and left out some parents.