Experience Salesforce
How to Write SOQL in APEX
What You’ll Learn
- SOQL Query
Topics
- SOQL Basics (Salesforce Object Query Language)
- How to Write SOQL in APEX
- SOQL Variable Binding in APEX
- SOQL Keywords
- Date Literals in SOQL
- SOQL Aggregate Functions
- 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 Extra Support? Our FREE study materials have got you covered.
Our expert-prepared study materials provide the answers you need. Clear your doubts and improve your skills with detailed notes from industry professionals.