SOQL Cheat Sheet

By Wes Lyons November 12, 2023

Here is a cheat sheet of common SOQL examples that can be used as reference -

Retrieve records

SELECT Id
FROM Contact

Group by

SELECT ShippingState, COUNT(Id)
FROM Account
GROUP BY ShippingState

Retrieve with junction

SELECT Id
FROM Contact
WHERE Id IN (
    SELECT ContactId
    FROM CampaignMember
    WHERE CampaignId = '701000000000000000'
)

Date literals

SELECT Id
FROM Contact
WHERE CreatedDate = TODAY

All date literals can be found here.

Parent and children

SELECT Id, Name, (SELECT Name FROM Contacts)
FROM Account

Pagination

SELECT Id, Name
FROM Account
ORDER BY Name DESC
LIMIT 50 OFFSET 0

Querying the next page -

SELECT Id, Name
FROM Account
ORDER BY Name DESC
LIMIT 50 OFFSET 50

Retrieve all fields

SELECT FIELDS(ALL)
FROM Account
LIMIT 200

Using the FIELDS function requires a LIMIT of 200 or less. The FIELDS function supports ALL, CUSTOM, or STANDARD.

Filtering aggregates

SELECT ContactId, COUNT(Id)
FROM AccountContactRelation
GROUP BY ContactId
HAVING COUNT(Id) > 1