---
schema_version: "1"
id: 545fc0cf9c4e42a0d072df20c523f8c839cdd148b6f5baa752cb1f406cef9c08
title: |-
  Understanding Foreign Key and Parent-Child
      Relationship SOQL Queries
collection: legacydeveloper
version: current
locale: en-us
portal_url: https://docs.salesforce.com/legacydeveloper/current/en-us/apexcode/langCon_apex_SOQL_foreign_key.md
canonical_url: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_foreign_key.htm
source_site: developer.salesforce.com
content_type: documentation
content_hash: 32b843ed4a7ce1f3b17c80dc24120f6d91ecb6778af4b8281963b347161f0d07
---
# Understanding Foreign Key and Parent-Child Relationship SOQL Queries

The SELECT statement of a SOQL query can be any valid SOQL statement, including foreign key and parent-child record joins. If foreign key joins are included, the resulting sObjects can be referenced using normal field notation. For example:

System.debug(\[SELECT Account.Name FROM Contact
              WHERE FirstName = 'Caroline' WITH USER\_MODE\].Account.Name);

Additionally, parent-child relationships in sObjects act as SOQL queries as well. For example:

for (Account a : \[SELECT Id, Name, (SELECT LastName FROM Contacts)
                  FROM Account
                  WHERE Name = 'Acme'
                  WITH USER\_MODE\]) {
     Contact\[\] cons = a.Contacts;
}

//The following example also works because we limit to only 1 contact
for (Account a : \[SELECT Id, Name, (SELECT LastName FROM Contacts WITH USER\_MODE LIMIT 1)
                  FROM Account
                  WHERE Name = 'testAgg'\]) {
     Contact c = a.Contacts;
}

- [← Previous](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SObjects_field_relationships.htm "Accessing sObject Fields Through Relationships")
- [Next →](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_agg_fns.htm "Working with SOQL Aggregate Functions")