Sub topic 11
Querying external objects
This chapter covers how SOQL and Apex read external objects, what happens at the external system when you do, and the errors you are most likely to hit. It assumes you already know basic SOQL and Apex syntax. It also assumes you have an external data source and at least one external object, created with Validate and Sync as covered in earlier chapters. The examples use a hypothetical external object named Product__x.
How a query on an external object works
A query on a standard or custom object reads rows from the Salesforce database. A query on an external object does not. Salesforce Connect turns the SOQL statement into a live request to the external system through the adapter. For an OData adapter, that request is an HTTP call to the OData endpoint. The response is converted into external object records, and those records exist only for the duration of the request.
Three consequences follow from this model:
- Every query is a callout, so its speed depends on the external system and the network.
- Data is always current, because nothing is cached in Salesforce by default.
- Whatever the external system cannot do, the query cannot do. Salesforce only passes along what the adapter supports.
Writing SOQL for external objects
External objects use the __x suffix. Custom fields still end in __c. Two standard fields exist on every external object:
| Field | Purpose |
|---|---|
| `ExternalId` | Uniquely identifies the row in the external system. It is the record's ID. |
| `DisplayUrl` | A URL that Salesforce uses when it links to the record in the UI. |
A basic query looks like the ones you already know:
SELECT ExternalId, DisplayUrl, Name__c, Price__c
FROM Product__x
WHERE Price__c > 100
ORDER BY Name__c
LIMIT 20The WHERE, ORDER BY, and LIMIT clauses are sent to the external system when the adapter can apply them there. Pushing these clauses down is what keeps the response small. If a filter cannot be pushed down, Salesforce may have to fetch more rows and filter them itself, or the query may fail. For this reason, always include a selective WHERE clause and a LIMIT.
Select only the fields you need
Each selected field becomes part of the request. Selecting fewer fields means a smaller payload and, for some adapters, a smaller URL. Avoid listing every field out of habit.
Record IDs are not Salesforce IDs
The ExternalId value is a string from the external system, such as 1042 or a GUID. Salesforce also assigns each external object record an Id that is generated from the external ID. The Id is stable only as long as the external row exists. Do not store it as if it were a permanent Salesforce ID in a place that has no way to refresh it. If you need a durable link, store the ExternalId, or use a relationship field as described in the relationships chapter.
Querying from Apex
Apex can query external objects with inline SOQL, just as it does for any other object:
List<Product__x> products = [
SELECT ExternalId, Name__c, Price__c
FROM Product__x
WHERE Price__c > 100
LIMIT 20
];
for (Product__x p : products) {
System.debug(p.Name__c + ' costs ' + p.Price__c);
}Each row is read from the external system at query time. Dynamic SOQL with Database.query() also works. Bind variables work as they do elsewhere, and they are resolved before the request is sent.
Limits that apply in Apex
External object queries count against the same governor limits as other SOQL, and also against limits specific to external data:
- Apex SOQL queries on external objects count toward the total number of SOQL queries in a transaction.
- Each query makes a callout, so it also counts toward the callout limits and the maximum callout time.
- Salesforce Connect has its own hourly limits on callouts per external data source. A busy integration can reach them, and when that happens queries fail until the window resets.
Check the current values for your edition in the Salesforce documentation, because these limits change between releases.
Using `IN` instead of a loop
This pattern runs one query for many keys:
Set<String> wanted = new Set<String>{'1001', '1002', '1003'};
List<Product__x> rows = [
SELECT ExternalId, Name__c
FROM Product__x
WHERE ExternalId IN :wanted
];
Map<String, Product__x> byExternalId = new Map<String, Product__x>();
for (Product__x p : rows) {
byExternalId.put(p.ExternalId, p);
}The map lets later code look up each product without another callout.
What the adapter can and cannot do
SOQL support on external objects is narrower than on standard objects, and the gaps depend on the adapter and the external system. The table lists typical differences. Treat it as a checklist of things to test, not a guarantee.
| Feature | Behavior on external objects |
|---|---|
| `WHERE` on indexed or filterable fields | Usually pushed to the external system |
| `ORDER BY` | Works only if the external system can sort on the field |
| `LIMIT` | Applied by the external system when possible |
| `OFFSET` | Support varies by adapter |
| Aggregate functions such as `COUNT()` | Support varies by adapter and may be limited |
| `GROUP BY` | Not available or restricted on many adapters |
| Relationship queries across objects | Restricted. See the next section. |
| `FOR UPDATE` | Not supported |
If a query uses an unsupported feature, you usually get a runtime error rather than a silent fallback. Test every query shape you plan to ship against the real external system, not only a sandbox mock.
Relationship queries
External objects relate to other objects through external lookup and indirect lookup fields. You can read the relationship ID fields in a plain query. Traversing from an external object to a parent, or from a standard object to an external child, is more restricted than the same traversal between two internal objects.
Practical guidance:
- Query the external object and the related internal object separately, then join them in Apex using a map.
- Do not assume that parent-to-child subqueries work across the internal/external boundary. Try the exact query first.
- Remember that each separate query is a separate callout when it targets an external object.
Paging through large results
A single query returns at most the number of rows that the external system and the adapter allow. When you need more rows than one request returns, you page through them. With OData adapters, Salesforce Connect handles server-driven paging for you when it displays list views. In Apex you control the batch size yourself, using LIMIT and, where supported, OFFSET:
Integer pageSize = 50;
Integer pageNumber = 2;
List<Product__x> page = [
SELECT ExternalId, Name__c
FROM Product__x
ORDER BY Name__c
LIMIT :pageSize
OFFSET :(pageSize * pageNumber)
];
System.debug(page.size() + ' rows on page ' + pageNumber);Always add a stable ORDER BY when you page. Without it, the external system may return rows in a different order on each call, and rows can be skipped or repeated.
Common errors and how to read them
When a query fails, the message usually comes from one of three places: Salesforce, the adapter, or the external system.
- Callout or authentication failures. The external system rejected the request. Check the named credential, the external credential, and the permission set that grants access to the principal. A
401or403from the external system points here. - Unsupported query feature. The adapter cannot express the query, for example a function the OData service does not support. Simplify the query, or fetch the rows and compute the result in Apex.
- Timeouts and limit errors. The external system responded too slowly, or you reached a callout limit. Add filters, reduce the fields, reduce the rows, or move the work to asynchronous Apex.
- Invalid field or object. The external schema changed after the last sync. Run Validate and Sync again so Salesforce matches the current external schema.
Keep in mind that a query can succeed in the Developer Console and still fail for a user. Access to external objects and fields comes from permission sets, and an external data source can require per-user authentication. Test with the type of user who will actually run the code.
Handling failures in Apex
Because queries depend on a remote system, wrap important ones in error handling. A failed callout throws an exception that you can catch:
public with sharing class ProductService {
public static List<Product__x> expensiveProducts(Decimal minPrice) {
try {
return [
SELECT ExternalId, Name__c, Price__c
FROM Product__x
WHERE Price__c > :minPrice
LIMIT 50
];
} catch (Exception e) {
System.debug(LoggingLevel.ERROR, 'External query failed: ' + e.getMessage());
return new List<Product__x>();
}
}
}Returning an empty list hides the failure from the caller, so decide whether that is acceptable. For a user-facing page, it is often better to show a message that the external data is unavailable than to show an empty table that looks like "no results."
Testing code that queries external objects
Apex tests cannot make real callouts, and they cannot read live rows from an external system. Instead, a test uses a stand-in for the external records. A common approach is to wrap the query in a small class and replace it in tests, so your logic can run against records you build in memory:
@IsTest
private class ProductServiceTest {
@IsTest
static void filtersByPrice() {
List<Product__x> fake = new List<Product__x>{
new Product__x(Name__c = 'Widget', Price__c = 150),
new Product__x(Name__c = 'Gadget', Price__c = 50)
};
List<Product__x> result = new List<Product__x>();
for (Product__x p : fake) {
if (p.Price__c > 100) {
result.add(p);
}
}
System.assertEquals(1, result.size());
}
}This test checks the filter logic against in-memory records. For real coverage of the query itself, design your code so that the SOQL sits in one method that tests can bypass, and keep the business logic in methods that take a list as an argument.
Query design checklist
- Select only the fields you need.
- Filter on fields the external system can filter efficiently, and always set a
LIMIT. - Add a stable
ORDER BYwhen you page. - Never query inside a loop. Use
INand a map. - Test each query shape against the real external system.
- Handle callout failures explicitly.
Exercise
A trigger on Case runs for up to 200 records per batch. For each case it queries Product__x by ExternalId with a separate SOQL statement. What goes wrong, and how do you fix it?
Show answer
Each SOQL statement on an external object is a live callout, so 200 cases cause up to 200 callouts in one transaction. This risks reaching the SOQL query limit, the callout limit, and the time limit, and it is slow. Collect all the product ExternalId values into a Set, run one query with WHERE ExternalId IN :ids, put the results into a Map keyed by ExternalId, and look up each case's product in the map.
Exercise
A query on Product__x works in your Developer Console session but fails with an authorization error when a sales user runs the same Apex. Name two things to check.
Show answer
First, check that the sales user has a permission set granting object and field access to Product__x and its fields. Second, check the authentication setup. If the external data source uses per-user authentication, the user needs their own credentials, or the external credential principal must be granted to the user through a permission set.