November 9, 2016 by LanceShi
2.3 Conditions inside where clause
In the where clause of SOQL query, we can do more complicated filtering than simply equal to or comparison. In the below section, I will introduce you about like, in and logical operators.
Example of like:
Select AccountId, FirstName, lastname From Contact Where lastname like 'appl%'
The above code means if the last name starts with appl, get the contact info.
Like means when a text field matches a specified pattern, then it will be true. And in the like string:
- The % wildcard matches zero or more characters.
- The _ wildcard matches exactly one character.
To give you an example. ‘Hell_’ will match ‘Hello’ but will not match ‘Hello world’. But ‘Hell%’ will match both.
Example of in:
Select Name From Account Where BillingState IN ('California', 'New York')
The above code means the BillingState can be either ‘California’ or ‘New York’. When you need your field can be any value in a certain list, in will be very handy.
Example of logical operators:
Select Id From Contact Where (LastName = 'foo' Or FirstName='test') And Account.Name = 'bar'
The above code means the contact’s Account name has to be ‘bar’. And it will match either the lastName is ‘foo’ or the firstName is ‘test’. We can use parenthesis to tell Apex which logic should go first.
In our transaction object, select the transactions where merchandise name begins with ‘Sample Test’, and the related customer’s name is ‘David’