Sub topic 10
Querying standard and custom objects with SOQL
This chapter assumes you know what objects, fields and records are, how API names work (including the __c and __r suffixes), and how lookup and master-detail relationships connect objects. It also assumes you have used SQL before. SOQL looks like SQL but has important differences, and most common mistakes come from treating it as the same language.
What SOQL is
SOQL (Salesforce Object Query Language) reads records from Salesforce objects. It is read-only: it never changes data. To create, update or delete records you use DML in Apex or an API call.
Key differences from SQL:
- You query one object at a time as the root of the query. There is no free-form
JOIN. You traverse relationships instead. - You use API names, not labels.
Invoice__cworks, but "Invoice" does not. - There is no
SELECT *. You list every field you need. (FIELDS(ALL)exists but has limits, described later.) - Results are always whole records with the Salesforce
Id, even if you do not select it explicitly in some contexts. - Security and sharing are enforced by the context you run in, not by the query text alone.
Basic query structure
A SOQL query has a required SELECT and FROM, plus optional clauses in a fixed order.
SELECT Id, Name, Industry
FROM Account
WHERE Industry = 'Technology'
ORDER BY Name ASC
LIMIT 10The same shape works for standard and custom objects. Only the API names change.
SELECT Name, Amount__c, Status__c
FROM Invoice__c
WHERE Status__c = 'Open'The clause order is SELECT, FROM, WHERE, WITH, GROUP BY, HAVING, ORDER BY, LIMIT, OFFSET. Putting them out of order causes a parse error.
Standard versus custom: what changes
| Aspect | Standard object (Account) | Custom object (Invoice__c) |
|---|---|---|
| Object API name | `Account` | `Invoice__c` |
| Custom field API name | `Region__c` | `Amount__c` |
| Standard field API name | `Name`, `Industry` | `Name`, `CreatedDate` |
| Child relationship name | `Contacts` | Defined when you create the relationship, usually `Invoices__r` |
| Parent relationship name | `Account` (for `AccountId`) | `Account__r` (for `Account__c`) |
Both kinds of object share system fields such as Id, CreatedDate, LastModifiedDate, OwnerId (when the object has an owner) and IsDeleted. A custom object in a master-detail child role has no OwnerId, because the parent controls ownership.
Filtering with WHERE
WHERE accepts comparison operators (=, !=, <, >, <=, >=), LIKE, IN, NOT IN, and the logical operators AND, OR, NOT.
SELECT Id, Name, Amount__c
FROM Invoice__c
WHERE Status__c IN ('Open', 'Overdue')
AND Amount__c > 1000
AND Name LIKE 'INV-%'Points to watch:
- String literals use single quotes. Double quotes are a syntax error.
- String comparisons are case-insensitive by default.
- Date and datetime literals are not quoted. Write
CreatedDate > 2026-01-01T00:00:00ZandCloseDate = 2026-06-30. - Date literals such as
TODAY,LAST_N_DAYS:30andTHIS_QUARTERsave you from computing dates. - Multi-select picklists use
INCLUDESandEXCLUDES, not=. - Comparing to null uses
= nullor!= null.
SELECT Id, Name, CloseDate
FROM Opportunity
WHERE CloseDate = THIS_QUARTER
AND AccountId != nullTraversing relationships
Relationship queries replace joins. There are two directions, and each uses a different syntax.
Child to parent: dot notation
When you query the child object, you can reach fields on the parent with dot notation. For a standard lookup such as Contact.AccountId, the relationship name is Account. For a custom lookup field Account__c, the relationship name replaces __c with __r.
SELECT Name, Amount__c, Status__c, Account__r.Name
FROM Invoice__c
WHERE Status__c = 'Open'Here Account__r.Name returns the Name of the parent Account. You can chain up to five levels of parent relationships, for example Account__r.Owner.Manager.Name.
You can also filter on parent fields:
SELECT Name, Amount__c
FROM Invoice__c
WHERE Account__r.Industry = 'Technology'Parent to child: subqueries
When you query the parent, you use a nested SELECT in parentheses. The FROM of the subquery is the child relationship name, which is plural for standard objects (Contacts, Opportunities) and ends in __r for custom children.
SELECT Id, Name, Industry,
(SELECT FirstName, LastName FROM Contacts)
FROM Account
WHERE Industry = 'Technology'
LIMIT 10For a custom child object, use the child relationship name that Salesforce assigned when the lookup or master-detail field was created. If the relationship name on the field is Invoices, the subquery is:
SELECT Name, (SELECT Name, Amount__c FROM Invoices__r)
FROM AccountYou can find the exact name in the lookup field definition under "Child Relationship Name", or in the object's describe result. It is the most common source of "Didn't understand relationship" errors.
Which suffix goes where
| You write | Meaning |
|---|---|
| `Account__c` | The lookup field itself. It holds the parent Id. |
| `Account__r` | The relationship to the parent record. Use it for dot notation. |
| `Invoices__r` | A child relationship name used in a subquery. |
| `Account` | The relationship name for the standard field `AccountId`. |
Result shape
The result of a relationship query is nested. In Apex, a parent-to-child query returns each parent with a list of children, and a child-to-parent query returns the parent as an SObject attached to the child.
List<Account> accounts = [
SELECT Id, Name, (SELECT FirstName, LastName FROM Contacts)
FROM Account
WHERE Industry = 'Technology'
LIMIT 10
];
for (Account a : accounts) {
System.debug(a.Name + ' has ' + a.Contacts.size() + ' contacts');
}If an account has no contacts, a.Contacts is an empty list, not null. By contrast, a parent reached through a lookup can be null when the lookup is empty, so inv.Account__r.Name throws a null pointer error if Account__c is blank. Check for null first.
Aggregates and grouping
SOQL supports COUNT(), COUNT(field), SUM, AVG, MIN, MAX and GROUP BY.
SELECT Status__c, COUNT(Id) total, SUM(Amount__c) amount
FROM Invoice__c
GROUP BY Status__c
HAVING SUM(Amount__c) > 5000Use an alias (total, amount) so the result is easy to read. Without one, Salesforce names the columns expr0, expr1 and so on. Use HAVING to filter on aggregate results, and WHERE to filter rows before grouping.
Semi-joins and anti-joins
Although SOQL has no JOIN, a subquery in WHERE filters by related records.
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT Account__c FROM Invoice__c WHERE Status__c = 'Open')This returns accounts with at least one open invoice. Use NOT IN for the opposite. The subquery must return a single Id or lookup field.
Ordering, limits and paging
ORDER BY Amount__c DESC NULLS LASTcontrols sort order and where nulls appear.LIMITcaps the number of rows. Apex synchronous code can retrieve at most 50,000 rows per transaction across all queries.OFFSETskips rows, but its maximum is 2,000, so it is unsuitable for deep paging. For large sets, filter onIdor use a query cursor orqueryMorein the API.- For very large volumes, use Bulk API or Batch Apex rather than one large query.
Security and sharing in queries
A query's visibility depends on where it runs.
- Apex runs in system mode by default, so object and field permissions are not applied unless you ask. Sharing rules depend on whether the class is declared
with sharing. - Add
WITH USER_MODEto enforce the running user's object permissions, field-level security and sharing. WITH SECURITY_ENFORCEDis an older option that checks field and object access, and throws an exception if a field is inaccessible.
List<Invoice__c> invoices = [
SELECT Name, Amount__c, Account__r.Name
FROM Invoice__c
WHERE Status__c = 'Open'
WITH USER_MODE
];If the user lacks read access to Amount__c, the query throws an exception instead of silently returning nothing for that field.
Dynamic and bind variables in Apex
Embed Apex variables in static SOQL with a colon. This is safe against injection.
String status = 'Open';
Decimal minimum = 1000;
List<Invoice__c> results = [
SELECT Id, Name
FROM Invoice__c
WHERE Status__c = :status AND Amount__c >= :minimum
];If you must build a query as a string with Database.query, prefer Database.queryWithBinds so values are still bound and not concatenated.
Map<String, Object> binds = new Map<String, Object>{ 'status' => 'Open' };
List<SObject> rows = Database.queryWithBinds(
'SELECT Id, Name FROM Invoice__c WHERE Status__c = :status',
binds,
AccessLevel.USER_MODE
);If you concatenate user input into a query string, escape it with String.escapeSingleQuotes. Bind variables are better.
Common errors
| Error message | Likely cause | Fix |
|---|---|---|
| `sObject type 'Invoice' is not supported` | You used the label, or omitted `__c`. | Use the API name `Invoice__c`. |
| `No such column 'Account__c' on entity 'Contact'` | The field is not on that object, or you lack field access. | Check the object and field-level security. |
| `Didn't understand relationship 'Invoices' in FROM part of query` | Wrong child relationship name. | Use the exact name, usually ending in `__r`. |
| `Non-selective query against large object type` | The filter is not indexed on a large object. | Filter on indexed fields such as `Id`, `Name`, lookups or external Ids. |
| `Too many query rows: 50001` | A transaction retrieved too many rows. | Add filters, or use Batch Apex. |
| `Variable does not exist` in Apex | A bind variable is misspelled or out of scope. | Check the variable name. |
Exercises
Exercise
You have a custom object Invoice_c with a lookup field Account_c to Account. Write one query that returns the invoice Name and the name of its Account, only for invoices whose Account has Industry 'Technology'.
Show answer
SELECT Name, Account_r.Name FROM Invoicec WHERE Accountr.Industry = 'Technology'. Dot notation with the _r relationship name reaches parent fields in both SELECT and WHERE.
Exercise
A query on Account contains the subquery (SELECT Name FROM Invoice__c). It fails. What is wrong, and how do you find the correct name?
Show answer
A parent-to-child subquery must use the child relationship name, not the object API name. Find it under Child Relationship Name on the lookup field, and use it as in (SELECT Name FROM Invoices__r).
Exercise
In Apex, inv.Account__r.Name throws a null pointer exception for some invoices. Why, and what is the fix?
Show answer
Account_c is empty on those invoices, so Accountr is null. Check inv.Accountr != null before reading Name, or filter the query with WHERE Account_c != null.