Apex SOQL (Salesforce Object Query Language)
Introduction
SOQL (Salesforce Object Query Language) is like SQL, but tailored for Salesforce data. It is used to retrieve records from Salesforce objects, such as Account, Contact, Lead, or even custom objects like Student__c.
SOQL is used inside Apex code, anonymous windows, and developer console when you want to filter, sort, or extract data from your Salesforce org.
Basic SOQL Syntax:
SELECT field1, field2 FROM ObjectName WHERE condition
Example:
SELECT Name, Industry FROM Account WHERE Industry = ‘Technology’
Key SOQL Clauses:
Clause | Purpose |
---|---|
SELECT | Choose which fields you want to retrieve |
FROM | Specify the object you want to query from |
WHERE | Add conditions to filter results |
ORDER BY | Sort results (ASC/DESC) |
LIMIT | Limit number of records returned |
LIKE | Search using wildcards % or _ |
Real-Life Analogy
Think of SOQL like searching a contact list:
When you type a name in your phone’s contact search, you’re doing something similar to:
SELECT Phone FROM Contacts WHERE Name = ‘Adnan’
It’s like asking Salesforce to look through its records and give you just the info you need.
Code Example
1: Simple Query
List<Account> accList = [SELECT Id, Name FROM Account WHERE Name = ‘Edge Communications’];
System.debug(accList);
Code Explanation:
• Queries all Account records where Name = ‘Edge Communications’.
• The result is stored in a List<Account>.
Output:
(Id=001XXXXXXXXXXXX, Name=Edge Communications)
2: Query with LIMIT and ORDER BY
List<Account> accList = [SELECT Id, Name FROM Account WHERE Name = ‘Edge Communications’];
System.debug(accList);
Code Explanation:
• Retrieves the latest 3 contacts created in Salesforce.
• Uses ORDER BY CreatedDate DESC and LIMIT 3.
Output:
John Doe
Alice Smith
Mark Taylor
3: Using SOQL with Custom Object
List<Student__c> students = [SELECT Name, Grade__c FROM Student__c WHERE Grade__c >= 80];
for(Student__c s : students) {
System.debug(s.Name + ‘ scored ‘ + s.Grade__c);
}
Code Explanation:
• Queries custom object Student__c.
• Filters students who scored 80 or more in Grade__c (custom field).
Output:
Adnan scored 85
Sara scored 90