Experience Salesforce

How to Write SOQL in APEX

What You’ll Learn

  • SOQL Query

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.
Salesforce Developer
Next Topic

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.

cts-img
Rakshabandhan Sale