SOQL Queries Explained: From Basics to Advanced Techniques
By Firus Hanov · · 7 min read
A comprehensive guide to SOQL (Salesforce Object Query Language) covering everything from basic SELECT statements to advanced relationship queries, aggregate functions, and performance optimization.

What is SOQL?
SOQL (Salesforce Object Query Language) is the query language used to search your Salesforce org's data. Similar to SQL but designed specifically for the Salesforce platform, SOQL lets you retrieve records from standard and custom objects with powerful filtering and relationship traversal.
Basic SELECT Queries
Every SOQL query starts with a SELECT statement:
// Basic query - get account names
SELECT Name FROM Account
// Multiple fields
SELECT Name, Industry, AnnualRevenue FROM Account
// With a filter
SELECT Name, Email FROM Contact WHERE AccountId != null
Key difference from SQL: You cannot use SELECT * in SOQL. You must explicitly list every field you want to retrieve.
WHERE Clauses and Operators
SOQL supports rich filtering with these operators:
- Comparison:
=,!=,<,>,<=,>= - String matching:
LIKEwith%and_wildcards - Set membership:
IN,NOT IN - Null checks:
= null,!= null - Date literals:
TODAY,LAST_N_DAYS:30,THIS_YEAR
// String matching
SELECT Name FROM Account WHERE Name LIKE 'Acme%'
// IN operator
SELECT Name FROM Account WHERE Industry IN ('Technology', 'Finance')
// Date literals
SELECT Name, CreatedDate FROM Opportunity
WHERE CreatedDate = LAST_N_DAYS:90
Relationship Queries
One of SOQL's most powerful features is querying across object relationships.
Child-to-Parent (Dot Notation)
// Get contact's account name
SELECT Name, Account.Name, Account.Industry
FROM Contact
WHERE Account.Industry = 'Technology'
Parent-to-Child (Subquery)
// Get accounts with their contacts
SELECT Name, (SELECT Name, Email FROM Contacts)
FROM Account
WHERE Industry = 'Technology'
Aggregate Functions
SOQL supports aggregate functions for data analysis:
// COUNT
SELECT COUNT() FROM Account WHERE Industry = 'Technology'
// GROUP BY with aggregates
SELECT Industry, COUNT(Id) numAccounts, SUM(AnnualRevenue) totalRevenue
FROM Account
GROUP BY Industry
HAVING COUNT(Id) > 5
// Other aggregates: AVG(), MIN(), MAX()
ORDER BY and LIMIT
// Sort results
SELECT Name, AnnualRevenue FROM Account
ORDER BY AnnualRevenue DESC NULLS LAST
// Limit results
SELECT Name FROM Account ORDER BY CreatedDate DESC LIMIT 10
// Pagination with OFFSET
SELECT Name FROM Account ORDER BY Name LIMIT 10 OFFSET 20
SOQL For Loops
When processing large datasets, use SOQL for loops to avoid heap size limits:
// Processes records in chunks of 200
for (Account acc : [SELECT Id, Name FROM Account WHERE Industry = 'Technology']) {
// Process each account
acc.Description = 'Tech company';
}
// Even better for very large datasets
for (List<Account> accounts : [SELECT Id, Name FROM Account]) {
// Process in batches of 200
update accounts;
}
Dynamic SOQL
Build queries dynamically at runtime using Database.query():
String objectName = 'Account';
String fieldName = 'Industry';
String fieldValue = 'Technology';
String queryStr = 'SELECT Id, Name FROM ' + objectName +
' WHERE ' + fieldName + ' = :fieldValue';
List<SObject> results = Database.query(queryStr);
⚠️ Security warning: Always use bind variables (:variable) to prevent SOQL injection. Never concatenate user input directly into query strings.
Performance Tips
- Use selective filters — queries on indexed fields (Id, Name, CreatedDate, custom external IDs) perform best
- Avoid non-selective queries — filtering on non-indexed fields with large result sets causes full table scans
- Query only needed fields — don't retrieve fields you won't use
- Use LIMIT — always limit results when you don't need all records
- Avoid SOQL in loops — query once before the loop, then iterate over results
- Use the Query Plan tool — available in Developer Console to analyze query performance
Governor Limits for SOQL
| Limit | Synchronous | Asynchronous |
|---|---|---|
| Total SOQL queries | 100 | 200 |
| Records retrieved | 50,000 | 50,000 |
| Query rows in SOQL for loop | 50,000 | 50,000 |
Conclusion
Mastering SOQL is essential for every Salesforce developer. Start with basic queries, practice relationship queries and aggregates, and always keep performance and governor limits in mind. Practice writing SOQL queries daily to build fluency — try the coding challenges on ApexSensei to sharpen your skills.