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:
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:
- Go to https://workbench.developerforce.com/login.php
- Login to your production/sandbox org using your credentials.
- When you login for the first time the app will prompt to give permissions to execute data in Salesforce, click allow.
- After workbench opens, go to “utilities →APEX execute” to open the anonymous code editor.
- 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