Sub topic 1
How Salesforce objects relate: lookup and master-detail
Prerequisites
Assume you know basic SOQL: SELECT, FROM, WHERE, ORDER BY, and LIMIT. You should also know that Salesforce records have fields and IDs.
Lookup and master-detail relationships
A relationship connects records on two Salesforce objects. A child object stores a reference to a parent record in a relationship field.
- A lookup relationship is a flexible link. The child can often exist without a parent.
- A master-detail relationship is a stronger link. The detail record depends on its master for ownership, sharing, and often its lifecycle.
For example, Contact.AccountId points from a contact to its account. The relationship lets SOQL query fields in either direction.
Relationship names: `__r` suffixes and plural child names
The field name and relationship name are related but are not always identical.
For a custom lookup field named Project__c, the relationship name used to reach the parent is usually Project__r:
SELECT Id, Name, Project__r.Name
FROM Task__cFor a parent-to-child subquery, use the child relationship name. Standard objects commonly use names such as Contacts. Custom child relationship names often end in __r, such as Tasks__r. Check the relationship field's Child Relationship Name in Setup instead of guessing.
Child-to-parent: selecting parent fields with dot notation
A child-to-parent query starts from the child and follows parent fields with dots:
SELECT Id, LastName, Account.Name, Account.Owner.Name
FROM Contact
WHERE Account.Industry = 'Technology'
ORDER BY Account.NameAccount.Name reads a field on the contact's parent account. Account.Owner.Name walks through two relationships. If the lookup is empty, the parent value is null, so Apex code should use safe navigation when appropriate.
> callout note > Relationship queries do not copy parent fields into the child. They follow a relationship while Salesforce evaluates the query.
Filtering and sorting on parent fields
You can filter or sort child records by fields on their parent. This is useful when the result should contain children but the condition belongs to the parent. A missing lookup does not match a condition such as Account.Industry = 'Technology'.
Exercise
Which path reads the name of a Contact's Account?
Show answer
Use Account.Name, because Account is the parent relationship name and Name is the parent field.