Sub topic 5
Writing SOQL queries for export
This chapter assumes you know what Salesforce objects, records, and fields are. It also assumes you can run a command in a terminal and read a CSV file. Later chapters run these queries with Data Loader, the Salesforce CLI, and the Bulk API. Here you learn to write queries that export the right data.
What SOQL is and why export queries differ
SOQL (Salesforce Object Query Language) reads records from one object, plus related objects. It looks like SQL, with these differences:
- You query one primary object in the
FROMclause. There are no free-form joins. - There is no
SELECT *. You must list every field you want. - Relationships are followed by name, not by join conditions.
The last two points shape export work. A backup query must name its fields explicitly, so you need a list of the fields on each object. You can get one from Setup, from sf sobject describe, or from the describe call in the API.
Selecting explicit fields
A basic export query lists the fields and filters on LastModifiedDate. That filter is the basis for incremental exports, where you export only what changed since the last run.
SELECT Id, Name, Industry, OwnerId, CreatedDate, LastModifiedDate
FROM Account
WHERE LastModifiedDate >= 2026-01-01T00:00:00Z
ORDER BY LastModifiedDatePoints to note:
- Date-time literals use ISO 8601 format and are not quoted.
2026-01-01T00:00:00Zis in UTC. ORDER BY LastModifiedDatemakes the output predictable. You can record the last value you saw and start the next run from there.- Always export
Id. It is the key you need to rebuild relationships on restore. - Export
OwnerId,CreatedDate, and lookup fields too. Without them a restored record loses who owned it and what it pointed to.
Incremental exports and their gap
Use >= rather than > when you resume from a saved timestamp. Several records can share the same LastModifiedDate, and > can skip those that were not yet exported. The cost is that one or more records appear twice, so deduplicate on Id when you merge files.
An incremental export only sees records that still exist. It does not see deletions, and it does not see changes to fields that do not update LastModifiedDate. Plan a periodic full export alongside incremental ones.
Reading parent fields and child records
SOQL follows relationships in two directions.
- Child to parent uses dot notation, such as
Account.Nameon a Contact. - Parent to child uses a subquery in parentheses, using the child relationship name, such as
Tasks.
SELECT Id, FirstName, LastName, Account.Name,
(SELECT Id, Subject FROM Tasks)
FROM Contact
LIMIT 100The result is nested. Each Contact carries a list of its Tasks. That is fine for JSON from the API, but flat CSV tools such as Data Loader cannot export subquery results.
For backups, do not use subqueries. Export each object with its own query and keep the relationship Ids as columns. For example, query Task on its own and include WhoId and WhatId. You can join the files later by matching those Ids to the Id column of the parent file.
Parent fields reached by dot notation are still useful for readability. Treat them as extra, not as the data you rely on. The Id of the parent (AccountId) is what you restore from.
Relationship names to watch for
- Standard child relationship names are plural, such as
Contacts,Opportunities,Tasks. - Custom relationships end in
__rfor the parent side, and the lookup field itself ends in__c. A custom lookup fieldRegion__cis followed asRegion__r.Name. - Polymorphic fields such as
Task.WhoIdcan point to several object types. Export the Id itself, and useTYPEOFonly when you need to read type-specific fields.
Counting to check completeness
Before and after an export, count the records. A count query returns the number only.
SELECT COUNT() FROM AccountCompare the result with the number of data rows in the CSV file, not counting the header row. If an export is filtered, apply the same WHERE clause to the count. A later chapter on verification builds on this.
Counts can also warn you about volume. A query that returns millions of rows needs a different tool than one returning thousands, which later chapters cover.
Filtering safely
Useful filters for export work:
| Goal | Clause |
|---|---|
| Changed since a date | `WHERE LastModifiedDate >= 2026-01-01T00:00:00Z` |
| Created in a window | `WHERE CreatedDate >= 2025-01-01T00:00:00Z AND CreatedDate < 2026-01-01T00:00:00Z` |
| Slice by Id range | `WHERE Id > '001000000000000AAA' ORDER BY Id` |
| Active only | `WHERE IsDeleted = false` |
| Limit rows while testing | `LIMIT 100` |
Slicing by creation date or by Id splits a very large object into several smaller queries. Use half-open ranges (>= start, < end) so slices do not overlap and do not leave gaps.
String values are quoted with single quotes. If a value contains a quote, escape it with a backslash. If you build queries in a script from untrusted input, validate it first so it cannot change the meaning of the query.
Fields that cause trouble
Some fields need care in a backup:
- Compound fields such as
BillingAddressandNameon Contact. Query the component fields (BillingStreet,BillingCity, and so on) instead of the compound field when you want a file you can reload. - Formula fields are computed, so they cannot be restored. Export them for reference if you like, but exclude them from restore files.
- System fields such as
CreatedDateandLastModifiedByIdcan be written during an import only if your org has the setting that allows setting audit fields. Check this before you depend on it. - Long text and rich text fields can be large. Large values affect file size and batch settings.
- Binary content such as files and attachments is stored in separate objects (
ContentVersion,Attachment) and needs its own export method.
A good habit is to generate the field list from a describe call and then remove the fields you cannot write. Keep that list in version control with the queries.
Where the query runs
The same SOQL runs in several tools, and each has its own limits.
- The Developer Console Query Editor and Workbench are good for trying a query.
- Data Loader exports flat CSV and rejects subqueries.
sf data queryruns the query from the command line and can output CSV.- A Bulk API 2.0 query job runs the query asynchronously and suits large results.
Test a query with LIMIT 100 first. Remove the limit only after the columns look right.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `No such column` | The field name is wrong, or your profile cannot see the field | Check the API name and field-level security |
| `Unknown relationship` | Wrong relationship name in a subquery | Look up the child relationship name for the object |
| Missing rows | Filter on `>` or a gap between slices | Use half-open ranges and `>=` when resuming |
| Duplicate rows | `>=` boundary overlap in incremental runs | Deduplicate on `Id` |
| Subquery error in Data Loader | CSV export cannot flatten nested results | Query each object separately |
| Missing fields in the file | The user running the export lacks field access | Run as a user with access to every field |
The last two rows matter for backups. An export run by a user without access to some fields can finish with no error and still leave those fields out. Run backups as a dedicated user whose profile or permission set can read all the objects and fields you need, and check the column list after the first run.
Exercise
You export Task records with a subquery on Contact: SELECT Id, (SELECT Id, Subject FROM Tasks) FROM Contact, and your tool is Data Loader. The export fails. Rewrite the plan so that you can export the same information as flat CSV files and still link each task to its contact later. Name the query and the columns you need.
Show answer
Export Contact and Task as separate queries. For example, SELECT Id, FirstName, LastName, AccountId FROM Contact and SELECT Id, Subject, WhoId, WhatId FROM Task. Data Loader cannot flatten subquery results. Task.WhoId holds the Id of the related Contact (or Lead), so you can match it to the Contact Id column to link the files later.
Exercise
You resume an incremental export from the saved timestamp 2026-03-01T10:00:00Z. Should the filter use > or >=, and what must you do afterward?
Show answer
Use >=. Several records can share the same LastModifiedDate, and > could skip some that were not yet exported. This can produce duplicates, so deduplicate the merged files on Id.