SOQL in APEX code

We learnt a while ago, how we can execute SOQL queries to return data on the fly in Developer Console, and Workbench. And now that we have learnt most of the SOQL features, we finally see the use of SOQL queries inside Apex programming language. Apex is Salesforce’s own programming language similar to JAVA in operation which runs and operates on Salesforce servers.

We can run apex code directly in Workbench or Developer Console to test apex code. In actual scenarios, the code will be written inside apex classes inside methods or functions and called via Visualforce Pages, Lightning Components, Object Triggers, etc.

Here is a sample snippet of Apex code using a simple SOQL query to fetch 10 patients:

List<Contact> contactList = [SELECT Id, Name
  FROM Contact
  ORDER BY Name DESC
  LIMIT 10];
for(Contact con :contactList){
  System.debug('Name:' + con.Name);
}

When you run this as an anonymous block inside workbench, you will see the first 10 contacts in descending order with their name being printed.

Key Things to know:

  • SOQL query is written in square brackets inside apex.
  • SOQL query returns a list of records which can be stored inside List data structure of Apex.
  • Only the fields mentioned in the query are retrieved and if we try to access a field other than the specified fields, we may get a runtime error. For eg, system.debug(con.email) will throw an error.

Steps to execute this Apex Code in workbench:

  1. Go to https://workbench.developerforce.com/login.php
  2. Login to your production/sandbox org using your credentials.
  3. When you login for the first time the app will prompt to give permissions to execute data in Salesforce, click allow.
  4. After workbench opens, go to “utilities →APEX execute” to open the anonymous code editor.
  5. Enter your apex code and click on Execute.

Fig How to open anonymous apex window in workbench

Fig: How to execute an anonymous apex code snippet