Intermediate 25 min read

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

AccountId on Contact is the relationship field itself — it's just an Id value pointing at a specific Account record, not the Account record'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

Querying Account.Name and Account.Industry alongside the Contact's own fields lets you reach straight through to the parent record's data with dot notation — con.Account.Name — without a second, separate query. (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

AccountId and Account are related but distinct: AccountId always exists once a Contact has a parent, but con.Account (and anything under it) is only populated if the query explicitly asked for it — trying to read con.Account.Name without having queried Account.Name throws 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

APEX

Relationships in Apex Quiz

1. What does con.AccountId hold?

Log in to submit the quiz and save your score.

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.