Salesforce Dictionary - Free Salesforce GlossarySalesforce Dictionary
DictionaryFForeign Key
DevelopmentAdvanced

Foreign Key

A foreign key in Salesforce is a field on one object that stores the 18-character record ID of a row on another object, creating a link between the two.

§ 01

Definition

A foreign key in Salesforce is a field on one object that stores the 18-character record ID of a row on another object, creating a link between the two. Salesforce never exposes the raw database constraint and never lets you define a bare foreign key by hand. The platform builds one for you when you add a Lookup or Master-Detail relationship field to an object. The field shows the parent record's name in the user interface and quietly stores the parent's ID underneath.

Every standard parent-child link in Salesforce uses this pattern. Opportunity.AccountId is the foreign key from Opportunity to Account, and Contact.AccountId is the foreign key from Contact to Account. Custom Lookup and Master-Detail fields produce the same thing on custom objects, such as Invoice_Line__c.Invoice__c. These keys also power SOQL relationship queries and the polymorphic fields on standard objects like Task.WhatId, which can hold the ID of more than one object type.

§ 02

How foreign keys actually work in Salesforce

Lookup versus Master-Detail

Both relationship field types create a foreign key, but the constraint behind each one differs. A Lookup is a soft foreign key. The child field is usually optional, deleting the parent does not remove the child by default, and you can set the field to clear or to block the delete. Ownership and sharing on the two objects stay independent. A Master-Detail is a hard foreign key. The child field is required, the child inherits ownership and sharing from the parent, and deleting the parent deletes the children with it. A child in a Master-Detail cannot be reparented unless Allow Reparenting is turned on for that field. Salesforce documents the limits clearly. A detail object can have at most two Master-Detail relationships, and each object can hold many Lookup fields up to the per-object cap. Picking the right type early matters because converting a populated Lookup to Master-Detail (or back) has strict requirements and is not always possible. Treat the choice as a data-model decision, not a field setting you can flip later without consequences.

Polymorphic foreign keys

Most foreign keys point at exactly one object. A polymorphic foreign key can point at several. Task.WhatId is the classic example. It stores the ID of an Account, an Opportunity, a Case, or any custom object the admin has enabled for activities. Event.WhatId and Task.WhoId (Contact or Lead) work the same way. The platform figures out which object a stored ID belongs to by reading the three-character prefix at the start of the ID, so 001 means Account and 006 means Opportunity. SOQL handles a polymorphic key with the TYPEOF clause and its WHEN branches, letting one query select different fields depending on which object the row points at. Apex resolves the target at runtime, often by checking the ID prefix or by calling getSObjectType on the looked-up record. Reports and list views can struggle with these fields because the related object is not fixed. Document every polymorphic key in your schema notes. They look like ordinary reference fields until a query or an automation has to branch on the parent type, and the surprise tends to land in production.

External IDs as an alternate key

Foreign keys store Salesforce IDs, but data arriving from another system usually carries that system's own identifier instead. An External ID is a custom field flagged as a unique alternate key on the object, often a legacy primary key or an ERP account number. Mark the field as External ID and Unique, then load with an upsert. The upsert matches incoming rows on the external value, finds the matching Salesforce record, and writes the standard foreign key for you. Without an External ID, every integration has to run a query to resolve each parent ID before it can write the child, which is slower and error prone. External IDs also let you reference a parent by its external value directly in some load tools, so a child file can name its parent without ever knowing the Salesforce ID. A field can be both an External ID and the matching key for an upsert at the same time. This single feature removes most of the lookup gymnastics that integrations would otherwise need, and it is the standard pattern for any migration that loads parents and children in separate passes.

Indirect Lookup for external objects

Salesforce Connect surfaces data that lives outside the org as External Objects, and those use a different kind of foreign key. An Indirect Lookup field links a child standard or custom object to an External Object by matching a value against an External ID field on the parent. This is the only relationship field that does not store a Salesforce ID at all. It stores the matching external value and resolves the join at query time against the remote system. There is also an External Lookup, which links a child External Object to a parent External Object using the parent's External ID. Both depend on the external source being indexed well, because the join runs live rather than against a local index. Performance is therefore tied to how the source system handles the lookup, and a poorly indexed external table can make these queries slow. Indirect Lookup matters whenever you need standard Salesforce records to relate to rows that you never copied into the platform. It keeps the data in the system of record while still letting users open a related list and see the connected external rows.

Traversing foreign keys in SOQL

Once a foreign key exists, SOQL lets a query walk it with dot notation. SELECT Name, Account.Name, Account.Owner.Email FROM Opportunity follows Opportunity to Account to the account owner in a single query, and the platform generates the joins for you. This child-to-parent traversal has firm limits. In API version 58.0 and later you can go up to five levels deep, so Contact.Account.Owner.Manager.Name is valid. A single query can reference up to 55 child-to-parent relationships in total. Going the other direction, from a parent down to its children, uses a subquery instead of dot notation, as in SELECT Name, (SELECT LastName FROM Contacts) FROM Account. A query can include up to 20 of these parent-to-child subqueries. The relationship name in the query is not always the field name. Custom relationships use the field name with __r in place of __c, and standard parent links use the singular object name. Knowing which direction needs dot notation and which needs a subquery is one of the first things that trips up people writing SOQL against an unfamiliar schema.

Foreign keys, sharing, and roll-up summaries

The relationship type you pick decides far more than how two records link. A Master-Detail foreign key ties the child's security to the parent. The child inherits the parent's org-wide default, role-based sharing, and object access, and it has no owner field of its own. A Lookup foreign key transfers none of that. Each object keeps its own sharing model and the link is purely structural. Master-Detail also enables Roll-Up Summary fields on the parent, which count, sum, or find the minimum or maximum of a field across the related children. A Lookup cannot drive a standard roll-up summary, which is one of the most common reasons teams choose Master-Detail even when a Lookup would otherwise fit. Junction objects, which model a many-to-many relationship, are built from two Master-Detail keys on a single child object, and the first one created becomes the primary that controls ownership. Because these behaviors are baked in at field creation, the relationship type is one of the most consequential decisions in any data model. Get it right at design time and you avoid expensive rework once real data and sharing rules are in place.

Cascade deletes and orphan records

What happens to the child when the parent is deleted depends entirely on the foreign key type. A Master-Detail key cascades. Delete the parent and the children move to the Recycle Bin with it, then disappear when the bin is emptied or expires. A Lookup key gives you a choice when you create or edit the field. You can block the delete so the parent cannot be removed while children reference it, or you can let the delete proceed and clear the lookup on each child, which leaves those children as orphans with an empty parent field. Cascade delete on a Lookup is available only in limited cases and may require Salesforce to enable it. Orphaned children are usually a data-quality problem, since a record meant to belong to a parent now points at nothing. Reports and automation that assume a parent will fail or silently skip those rows. Decide the behavior at field creation, because changing it later does not retroactively fix records that were already orphaned. For required business relationships, blocking the delete or using Master-Detail is the safer default.

§ 03

How to create a foreign key in Salesforce

You never create a raw foreign key in Salesforce. You create a relationship field, and the platform builds and manages the key for you. Here is how to add one to an object.

  1. Open the child object in Object Manager

    In Setup, go to Object Manager and select the object that will hold the foreign key, the child. The relationship field always lives on the child side, the many side of the relationship.

  2. Create a new field of type Lookup or Master-Detail

    Go to Fields and Relationships, click New, then choose Lookup Relationship for a soft key or Master-Detail Relationship for a hard key. Pick based on whether the child can exist without the parent.

  3. Choose the parent object

    Select the object the key points at. This becomes the related-to object. For a polymorphic standard field you cannot create this yourself; those ship with the platform on objects like Task and Event.

  4. Set the delete behavior and field-level security

    For a Lookup, choose what happens when the parent is deleted: clear the field, block the delete, or cascade if allowed. Set field-level security and add the field to the page layouts.

  5. Save and load data with the IDs populated

    Save the field. When you import records, populate the relationship column with the parent's record ID, or use an External ID on the parent and load with upsert so the key fills automatically.

Key options
Relationship typeremember

Lookup for an optional, independent link; Master-Detail for a required link where the child inherits sharing and the parent supports roll-up summaries.

Parent delete behaviorremember

On a Lookup, choose Clear the field, Don't allow deletion, or Cascade delete (limited). Master-Detail always cascades to children.

Allow Reparentingremember

A Master-Detail option that lets the child move to a different parent after creation. Off by default, which locks the child to its original parent.

Child relationship nameremember

Sets the related list label and the SOQL relationship name used for parent-to-child subqueries from the parent object.

Gotchas
  • A detail object can have at most two Master-Detail relationships, so plan junction objects before you hit that ceiling.
  • Converting a Lookup to Master-Detail requires every child to have a parent populated first; orphan rows block the change.
  • The relationship field goes on the child object, not the parent. Adding it to the wrong object is a common first mistake.
  • Master-Detail makes the field required and the child inherit sharing, which can surprise teams expecting the looser Lookup behavior.
§

Trust & references

Sources

Cross-checked against the following references.

Official documentation

Straight from the source - Salesforce's reference material on Foreign Key.

Was this entry helpful?
Help us write better definitions. Quick reactions or detailed edit suggestions.

About the Author

Dipojjal Chakrabarti is a B2C Solution Architect with 29 Salesforce certifications and over 13 years in the Salesforce ecosystem. He runs salesforcedictionary.com to help admins, developers, architects, and cert/interview candidates sharpen their fundamentals. More about Dipojjal.

§

Test your knowledge

Q1. What is a Foreign Key in Salesforce?

Q2. What's an example of a foreign key field?

Q3. Why do foreign keys matter for SOQL?

§

Discussion

Loading…

Loading discussion…