Relationships in Apex
By the end of this lesson, you'll be able to:
- Access a parent record's field through a lookup or master-detail relationship
- Explain the dot-notation path used to traverse a relationship
- Recognize the difference between a relationship field (the Id) and the related record itself
Prerequisites: "Custom Fields"
A relationship field holds an Id
Contact con = [SELECT Id, LastName, AccountId FROM Contact LIMIT 1];
System.debug(con.AccountId); // an 18-character Id, like 001XXXXXXXXXXXXXXX
Contact con = [SELECT Id, LastName, AccountId FROM Contact LIMIT 1];— queries the relationship field directly.System.debug(con.AccountId);—AccountIdis the relationship field itself — just anIdvalue pointing at a specificAccountrecord, not theAccountrecord's actual data.
Traversing to the parent's fields
Contact con = [SELECT Id, LastName, Account.Name, Account.Industry FROM Contact LIMIT 1];
System.debug(con.Account.Name); // the parent Account's Name
System.debug(con.Account.Industry); // the parent Account's Industry
Contact con = [SELECT Id, LastName, Account.Name, Account.Industry FROM Contact LIMIT 1];— queryingAccount.NameandAccount.Industryalongside theContact's own fields.- (blank line)
System.debug(con.Account.Name);— reaches straight through to the parent record's data with dot notation, without a second, separate query.System.debug(con.Account.Industry);— same pattern for a second parent field.
(SOQL relationship queries get a full module of their own shortly.)
The relationship field vs the related record
con.AccountId; // the parent's Id only — a simple relationship field
con.Account; // the full related Account record (if queried)
con.Account.Name; // a specific field on that related record
con.AccountId;— always exists once aContacthas a parent — just the Id.con.Account;— the full relatedAccountrecord, but only populated if the query explicitly asked for it.con.Account.Name;— a specific field on that related record — trying to read this without having queriedAccount.Namethrows a runtime error.
Exercise
Write a SOQL query on Contact that selects Id, LastName, and the parent Account's Name and Industry, then debug the parent Account's Name for the first result.
Show hint
SELECT Id, LastName, Account.Name, Account.Industry FROM Contact LIMIT 1
Relationships in Apex Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A relationship connects one record to another — Apex lets you traverse from a child record straight to its parent's fields using dot notation, once the parent has been queried alongside it.