Sub topic 2
Lookup relationships: loose, optional links
A lookup relationship is the simplest way to connect two Salesforce objects. One record holds a reference to another record. The two records stay independent in almost every other way. This chapter explains how a lookup behaves, how to create one, what happens when the parent is deleted, and how to read and write lookup data in SOQL and Apex.
This chapter assumes you know the basic Salesforce data model (objects, fields, records) and can find your way around Setup and the Object Manager. You should also be able to read a basic SOQL SELECT statement. The parent and child vocabulary was introduced in the previous chapter. Here it is applied to one relationship type.
What a lookup is
A lookup relationship is a field on the child object that stores the Id of one record on the parent object. The field lives on the child. The parent object has no matching field. Salesforce instead builds a related list on the parent page and a child relationship name you can use in queries.
You already use lookups on standard objects. Contact.AccountId is a lookup to Account. Opportunity.AccountId is another. A custom lookup works the same way, and you can point it at a standard or a custom object.
The |o end of the line means a course has zero or one sponsor. The o{ end means an account can sponsor zero or many courses.
Key behaviors
A lookup is "loose" because the child does not depend on the parent. Four behaviors follow from that.
- The parent is optional by default. You can save a child record with the lookup field empty. You can mark the field required, either in the field definition or on a page layout.
- The child keeps its own owner. A child record in a lookup relationship has an Owner field, and that owner is not taken from the parent.
- The child has its own sharing. The child's visibility is set by its own sharing settings. Access to the parent does not grant access to the child, and the reverse is also true.
- There is no native roll-up summary field. You cannot define a roll-up summary on the parent for lookup children. The workarounds appear later in this chapter.
A lookup can also point at the same object, which is called a self-relationship. Account's ParentId field is an example. Custom objects can have a lookup to themselves, which is useful for hierarchies such as a category tree.
| Question | Lookup behavior |
|---|---|
| Is the parent required? | No by default. You can make it required. |
| Who owns the child? | The child has its own owner. |
| Who controls child sharing? | The child's own sharing settings. |
| What happens to the child when the parent is deleted? | Depends on the deletion option you pick. |
| Can the parent have a roll-up summary field? | No. |
| Can the lookup point to its own object? | Yes. |
Creating a lookup in Setup
You create the field on the child object. For a lookup from Course__c to Account:
- In Setup, open Object Manager and select
Course__c. - Open Fields & Relationships and click New.
- Choose Lookup Relationship and click Next.
- Pick the related object (Account) and click Next.
- Enter the field label (Sponsor). The field name becomes
Sponsor__c. - Choose whether the field is required, and choose the deletion behavior (next section).
- Optionally add a lookup filter to limit which parent records users can choose.
- Set field-level security, add the field to page layouts, and choose a related list label for the parent page.
The same field can be deployed as metadata. The deleteConstraint element stores the deletion option.
<?xml version="1.0" encoding="UTF-8"?>
<!-- force-app/main/default/objects/Course__c/fields/Sponsor__c.field-meta.xml -->
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Sponsor__c</fullName>
<label>Sponsor</label>
<referenceTo>Account</referenceTo>
<relationshipLabel>Sponsored Courses</relationshipLabel>
<relationshipName>Sponsored_Courses</relationshipName>
<required>false</required>
<deleteConstraint>SetNull</deleteConstraint>
<type>Lookup</type>
</CustomField>The relationshipName value becomes the child relationship name used in parent-to-child queries. In SOQL you write it with a __r suffix, here Sponsored_Courses__r.
What happens when the parent is deleted
You choose the behavior when you create the field. The options depend on whether the field is required.
- Clear the value of this field. The child record stays and its lookup becomes empty. This is the default. It is available only when the field is not required, because a required field cannot be left empty.
- Don't allow deletion of the lookup record that's part of a lookup relationship. Salesforce blocks the parent delete while any child points to it. This is the only option when the field is required.
When Salesforce blocks a delete, the operation fails. In Apex, a delete statement throws a DmlException with the status code DELETE_FAILED. The message names the related records that caused the block. If you use Database.delete with allOrNone set to false, you get a Database.DeleteResult instead and can read the errors.
Salesforce can also delete children together with the parent through a lookup, but this is not a self-service setting in the field wizard. Cascade delete is the main reason to use master-detail, which a later chapter covers.
Lookup filters
A lookup filter limits which parent records users can pick in the field. For example, the Sponsor lookup could allow only accounts whose Type is "Customer". The filter is defined on the field. It checks values when users select a record and when a record is saved. The next chapter covers filters in detail. For now, remember that a filter narrows the choices on one field without changing the relationship type.
Reading lookup data with SOQL
A lookup gives you two query directions. The relationship name for each direction differs, so keep the child field and the relationship name apart in your head.
Child to parent
In a child-to-parent query you use dot notation on the relationship name. For a standard lookup such as Contact.AccountId, the relationship name is Account. For a custom lookup Sponsor__c, the name is Sponsor__r.
SELECT Id, LastName, Account.Name
FROM Contact
WHERE Account.Industry = 'Technology'This query reads and filters on fields of the parent. You can traverse up to five levels of parents, such as Account.Owner.Manager.Name.
Because the lookup is optional, some children have no parent. In the select list, a contact with no account returns null for Account.Name. Salesforce does not raise an error. A WHERE condition on a parent field, as in the query above, drops those contacts, because null never equals 'Technology'.
Parent to child
In a parent-to-child query you write a subquery on the child relationship name. For Contact under Account, that name is Contacts.
SELECT Name, (SELECT LastName FROM Contacts)
FROM AccountEach account row carries a nested list of its contacts. Accounts with no contacts return an empty list. For a custom lookup, use the relationship name with __r, for example (SELECT Name FROM Sponsored_Courses__r).
The child relationship name is the plural label from the lookup field definition. Standard names like Contacts are fixed by Salesforce. If a query fails with an unknown relationship error, check the relationship name on the field detail page.
Creating linked records in Apex
In Apex you set the lookup by assigning an Id to the field. The parent must already exist, so insert it first, then use its Id. The field is optional, so you can also insert a child without it.
Account sponsor = new Account(Name = 'Northwind Training');
insert sponsor;
Course__c linked = new Course__c(Name = 'Apex Basics', Sponsor__c = sponsor.Id);
Course__c standalone = new Course__c(Name = 'Self-study Intro');
insert new List<Course__c>{ linked, standalone };
Course__c reloaded = [
SELECT Name, Sponsor__r.Name
FROM Course__c
WHERE Id = :standalone.Id
];
System.debug(reloaded.Sponsor__r); // null, because no sponsor was setReading reloaded.Sponsor__r.Name here would throw a NullPointerException, because Sponsor__r is null. When the parent might be missing, test for it first or use the safe navigation operator, reloaded.Sponsor__r?.Name.
Counting children without a roll-up summary
A lookup cannot have a native roll-up summary field. If you need a count or a total of children per parent, you have several options.
- An aggregate SOQL query that you run when you need the number.
- A record-triggered flow or an Apex trigger that recalculates a number field on the parent when children change.
- A managed or open-source roll-up tool, such as the Declarative Lookup Rollup Summaries package.
- Converting to master-detail, if the data rules allow it. A later chapter covers conversion.
An aggregate query is the lightest option. This one counts contacts per account for a set of account Ids. The Id shown is a placeholder.
Set<Id> accountIds = new Set<Id>{ '001000000000001AAA' };
List<AggregateResult> totals = [
SELECT AccountId, COUNT(Id) total
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
];
for (AggregateResult row : totals) {
System.debug(row.get('AccountId') + ' has ' + row.get('total') + ' contacts');
}Accounts with zero contacts do not appear in the result, because GROUP BY returns only groups that have rows. Treat a missing account as a count of zero in your code.
Common mistakes
- Putting the field on the wrong object. The lookup field goes on the child. If the field is on the wrong side, the "one parent, many children" shape inverts.
- Querying the field name instead of the relationship name.
Sponsor__cholds an Id. To reach parent fields, useSponsor__r.Name. The__cand__rsuffixes are different names for different things. - Assuming a parent exists. Optional lookups mean
nullparents are normal. Guard Apex code and expect parentless rows in query results. - Expecting sharing to follow the parent. A user who can see an account does not automatically see its lookup children. Check the child's own sharing settings.
- Relying on "clear the value" for data you must keep. Choose the block option when the link is important.
Exercise
A Course__c object has an optional lookup field Sponsor__c to Account, with the "clear the value" deletion option. A user deletes an Account that sponsors three courses. What happens to the three courses, and what does Sponsor__r.Name return for them in a later query?
Show answer
The three courses are not deleted. Salesforce sets Sponsor__c to empty on each of them. In a later query, Sponsor__r is null, so Sponsor__r.Name returns null in SOQL results. In Apex, reading Sponsor__r.Name directly on the record would throw a NullPointerException unless you check for null or use ?..
Exercise
You need the number of related Course__c records on each Account, and Sponsor__c is a lookup. Why can you not add a roll-up summary field to Account, and what is one way to get the count?
Show answer
Roll-up summary fields exist only on the master side of a master-detail relationship, and a lookup is not one. One way to get the count is an aggregate query such as SELECT Sponsor__c, COUNT(Id) total FROM Course__c WHERE Sponsor__c IN :accountIds GROUP BY Sponsor__c. Other ways are a record-triggered flow or trigger that updates a number field on Account, a roll-up tool, or converting the relationship to master-detail if the data allows it.