2.1 Use SOQL and where statement to retrieve data

The concept

In the last chapter, we have talked about how to use DML statements and Database methods to modify data from Salesforce database. In this chapter, I will show you how to retrieve data. Apex used a feature called SOQL language to retrieve the data. And SOQL statements are first class citizens in Apex as well.

If you are familiar with SQL, SOQL is very, very similar to that. If you are not, don’t worry, you don’t have to know that in order to follow this tutorial.

Look at the following sample code:


List<Merchandise__c> merList = [Select  Id, Name, 
                               		    Original_Price__c,
                               		    Discount_Type__c
                                From    Merchandise__c
                                Where   Original_Price__c > 100];

System.debug('The number of merchandise whose price is over 100 is: ' + merList.size());

for(Merchandise__c mer: merList) 
{
    System.debug('The Name of the Merchandise is: ' + mer.Name);
}

A bit explanation

The basic and most normal form of SOQL query consists of three parts, the Select clause, the From clause and the Where clause.

Select clause specifies which fields you want to retrieve from database. You must retrieve the fields before using them in the later code. If you are familiar with SQL, please note there is no Select * in SOQL.

From clause specifies which object you need to retrieve data from.

Where clause specifies the filtering conditions. It is really not the whole table you want to retrieve. Just part of it which specifies a certain criteria – the goods whose price is less than 100, the houses who have a open inspection this Saturday, the students who will sit a certain exam, etc. We will talk more about the conditions in where statement in Chapter 2.3.

SOQL query can return a list of SObjects as well as a single SObject if you are sure the return size will be only one. But it is almost always good to return to a list of Sobjects.

And please SOQL statements are treated as first class citizens in Apex. It is not just a String. We can use the string version to do Dynamic SOQL using Database methods. We will talk about that later on in this chapter.

Introducing query editor

In your developer console, there is a tab called Query Editor, and you can directly put SOQL query inside and execute. As shown below:

queryeditor

Exercise

Use SOQL query to retrieve merchandise with the name Book.

Next Post

2.2 Use relationship to retrieve data from related objects

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *