SOQL is the bridge between your logic and the physical data. It allows you to talk to the database and retrieve exactly what you need with surgical precision.
Retrieve data from a single object or cross-reference multiple objects that are related through parent-child lookups.
Power your logic by using SOQL to Count, Sort, and Group records based on complex business criteria.
Seamlessly retrieve data from all platform datatypes including Date, Checkbox, and Number.
Aggregate functions allow you to perform calculations on a set of records. Instead of returning individual rows, the database returns summarized data like totals, averages, or counts.
Returns the number of rows matching your criteria.
Calculates the total sum of a numeric field.
Finds the average value of a numeric field.
Retrieves the lowest or highest value in a set.
To summarize data by a specific field (like Stage or Industry), you must use GROUP BY. This is the foundation of Salesforce reporting.
SELECT LeadSource, COUNT(Name)
FROM Lead
GROUP BY LeadSource
Salesforce is a relational database. Use these patterns to traverse between objects without writing multiple queries, saving you from hitting governor limits.
When querying a child object (like Contact), use **Dot Notation** to reach up and grab data from the parent (like Account).
// Retrieve Contact with Parent Account Name
SELECT Name, Account.Name
FROM Contact
Rule: Use the Relationship Name + "." + Field Name
When querying a parent, use a **Subquery** inside parentheses to retrieve all related children in one go.
// Retrieve Account with all its related Contacts
SELECT Name, (SELECT LastName FROM Contacts)
FROM Account
Rule: Use the Child Relationship Name (usually plural)
In the Salesforce multi-tenant environment, limits are not suggestions—they are hard rules that ensure platform stability for everyone.
Per Transaction
Sync Queries (Limit)
Number of SOQL queries per transaction: 100 (sync). This means you cannot execute more than 100 SELECT statements in a single code execution path.
Total Records
Max Records (Limit)
Number of SOQL records returned per query: 50,000. Regardless of how many queries you run, the total records fetched cannot exceed this threshold.
Developer Best Practice: Never place a SOQL query inside a FOR loop. This is the fastest way to hit the 100-query limit. Always "bulkify" your code by querying once and storing results in a Map or List.
Test your knowledge with these common development scenarios. Mastering these patterns is essential for building efficient Salesforce applications.
Question: How do you retrieve the Name and Phone of all Accounts where the Industry is 'Technology' and the Account is active?
// The Solution
SELECT Name, Phone
FROM Account
WHERE Industry = 'Technology'
AND IsActive__c = true
Question: You need to get the 10 most recently created Contacts. How do you structure the query?
// The Solution
SELECT FirstName, LastName, CreatedDate
FROM Contact
ORDER BY CreatedDate DESC
LIMIT 10
Question: How can you retrieve an Account's name along with the names of all its related Contacts in a single query?
// The Solution (Inner Join)
SELECT Name, (SELECT LastName FROM Contacts)
FROM Account
Question: How do you find all Contacts whose birthday is recorded as today's date?
Pro Tip: Using the TODAY literal automatically handles timezones and formatting for you.
// The Solution
SELECT Name, Birthdate
FROM Contact
WHERE Birthdate = TODAY
Question: How do you retrieve all Accounts that are publicly owned and have a 'Hot' rating?
Database Tip: When filtering by text or picklist values in SOQL, always wrap the values in single quotes.
// The Solution
SELECT Name, Ownership, Rating
FROM Account
WHERE Ownership = 'Public'
AND Rating = 'Hot'
Question: How do you retrieve all Leads that are in the 'Working - Contacted' status and came from the 'Web' source?
Developer Note: For fields containing spaces like Working - Contacted, ensure the string inside the single quotes matches the picklist value exactly.
// The Solution
SELECT Name, Status, LeadSource
FROM Lead
WHERE Status = 'Working - Contacted'
AND LeadSource = 'Web'
Question: How do you retrieve all Contacts whose name is recorded exactly as 'Jane'?
Database Fact: While SOQL keywords like SELECT are case-insensitive, the string filter 'Jane' is often treated with precision depending on your org's collation settings.
// The Solution
SELECT Name, Email
FROM Contact
WHERE Name = 'Jane'
Question: How do you retrieve all Accounts where the Industry is 'Banking' OR the Ownership is 'Private'?
Logic Tip: Unlike the AND operator which requires both conditions to be true, the OR operator returns a record if either one of the conditions is met.
// The Solution
SELECT Name, Industry, Ownership
FROM Account
WHERE Industry = 'Banking'
OR Ownership = 'Private'
Question: How do you retrieve Accounts belonging to any of these three industries: 'Banking', 'Technology', or 'Business'?
Optimization Tip: Using IN is much cleaner and faster than writing multiple OR statements for the same field.
// The Solution
SELECT Id, Name, Industry, Ownership
FROM Account
WHERE Industry IN ('Banking', 'Business', 'Technology')
Question: How do you retrieve all Cases where the Subject line starts with the word 'Follow'?
Wildcard Tip: The % symbol represents zero or more characters. Placing it after your text finds records starting with that string.
// The Solution
SELECT Subject, Status, Priority
FROM Case
WHERE Subject LIKE 'Follow%'
Question: How do you display all Opportunities in your org, ensuring the ones with the highest revenue appear at the top?
Sorting Tip: The ORDER BY clause is always placed at the end of your query. Use DESC for highest-to-lowest and ASC for lowest-to-highest.
// The Solution
SELECT Amount, Id, Name
FROM Opportunity
ORDER BY Amount DESC
Question: How do you display exactly 10 Opportunities where the Close Date has already passed (is in the past)?
Efficiency Tip: The LIMIT operator is vital for performance. It prevents the database from returning thousands of records when you only need a small sample for your UI.
// The Solution
SELECT Name, CloseDate, StageName
FROM Opportunity
WHERE CloseDate < TODAY
LIMIT 10
Question: How do you retrieve all Accounts sorted alphabetically by Name, but excluding the first 5 records from the results?
Pro Tip: The OFFSET clause allows you to skip a specific number of rows before beginning to return records. This is essential for building "Load More" or "Next Page" buttons.
// The Solution
SELECT Name, Industry, Ownership
FROM Account
ORDER BY Name ASC
OFFSET 5
Question: How do you retrieve a count of how many Leads exist for every different Status in your organization?
Syntax Rule: When using an aggregate function like COUNT() with a field like Status, you must include that field in the GROUP BY clause.
// The Solution
SELECT Status, COUNT(Id)
FROM Lead
GROUP BY Status
Question: How do you find all Cases that were created within the current calendar month?
Date Literal: Using THIS_MONTH is dynamic; it automatically adjusts every time the month changes without you needing to update your code.
// The Solution
SELECT Subject, CreatedDate, Status
FROM Case
WHERE CreatedDate = THIS_MONTH
Question: How do you retrieve Tasks created between October 7th and November 15th?
Format Rule: For specific dates, SOQL requires the YYYY-MM-DD format. Since CreatedDate is a DateTime field, we append the time suffix T00:00:00Z.
// The Solution
SELECT Subject, CreatedDate
FROM Task
WHERE CreatedDate >= 2025-10-07T00:00:00Z
AND CreatedDate <= 2025-11-15T23:59:59Z