6
How to Write SOQL in APEX
Chapter Topics
- SOQL Basics (Salesforce Object Query Language)
- How to Write SOQL in APEX
- SOQL Variable Binding in APEX
- SOQL Keywords
- SOQL Date Literals In Salesforce
- SOQL Aggregate Query
- Child to Parent Relationship
- Parent to Child – Relationship Queries in SOQL
- SOQL Multi level Relationships
- SOQL Return Type
- Salesforce Dynamic SOQL
- SOQL βforβ Loops
SOQL Query
A SOQL query is equivalent to a SELECT SQL statement and searches the org database.
Example:
Select name from account // standard object
Select name, Student_name from student__c // custom object
But we cannot use an asterisk (*) in SOQL queries, which we can use in SQL.
OR, AND and WHERE Clause
Select Student_name from student__c where couse_opted__c = βSalesforce Adminβ;
Select Student_name from student__c where couse_opted__c = βSalesforce Admin and App Builderβ OR couse_opted__c = βSalesforce Developerβ;
Select Student_name from student__c where couse_opted__c = βSalesforce Admin and App Builderβ OR graduated__c = false;
Example:
public class Soql {
public static void main() {
List < Account > accList = [Select Name, NumberOfEmployees FROM Account];
for (integer i = 0; i < accList.size(); i++) {
System.debug(accList[i].numberOfEmployees);
}
// *** FOR EACH LOOP ***
for (Account a: acclist) {
System.debug('Acc Name = ' + a.Name + 'NumOfEmp = ' + a.numberOfEmployees);
}
}
}
Note:
- It is mandatory to mention the field in the SOQL query which you want to access in the Apex Code.
- Comparison of strings are case sensitive using theβ=β operator in soql.

Need more support?
Get a head start with our FREE study notes!
Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.