Sub topic 7
Including deleted records
This chapter assumes you can write basic SOQL and run an export with Data Loader or the Salesforce CLI. It covers how deleted records behave in an export and how to include them.
Why deleted records matter
A normal query returns only live records. When a user deletes a record, Salesforce moves it to the Recycle Bin and sets its IsDeleted field to true. The standard query operation hides these records. A backup that uses only query therefore has no copy of anything deleted before the export ran.
Records stay in the Recycle Bin for 15 days, or until the bin fills up. After that they are purged. Some records are never recoverable from the bin, such as those removed with a hard delete.
How a deleted record is represented
Every deleted record keeps its Id. You can filter on IsDeleted only in queries that are allowed to see deleted rows. The ALL ROWS keyword in SOQL does this when you run the query through the API:
SELECT Id, Name, IsDeleted, LastModifiedDate
FROM Account
WHERE IsDeleted = true
ALL ROWSWithout ALL ROWS, the same query returns zero rows, even when deleted accounts exist.
Choosing a tool
Each tool reaches deleted records differently.
| Tool | How to include deleted records |
|---|---|
| Data Loader | Choose **Export All** instead of **Export**. |
| Salesforce CLI | Add the `--all-rows` flag to `sf data query`. |
| Bulk API 2.0 | Set the job `operation` to `queryAll`. |
| Data Export Service | Does not include the Recycle Bin contents in the standard files. |
The CLI example below writes both live and deleted accounts to one file:
sf data query \
--query "SELECT Id, Name, IsDeleted FROM Account" \
--all-rows \
--result-format csv \
--target-org my-prod-alias > accounts-all.csvThe IsDeleted column tells you which rows were deleted. Keep it in your field list so that you can separate them later.
Common errors
- Zero rows for deleted records. You ran a plain query. Switch to
--all-rows,queryAll, or Export All. - Restoring deleted rows as new records. Loading a deleted row through insert creates a new record with a new Id. Use undelete if the record is still in the Recycle Bin, and use the original Id to relink children.
- Missing
IsDeletedin the export. You cannot tell live rows from deleted ones afterward. - Assuming archived data is covered. Archived tasks and events appear only with
queryAll.
Exercise
A nightly CLI export of Contact returns 40,000 rows, but a user says a contact deleted last week is missing. What change would include it, and which field would you add to the query?
Show answer
Add the --all-rows flag to sf data query so deleted rows are returned, and add IsDeleted to the SELECT list so you can tell deleted rows from live ones.