Tag Archives: SOQL

Querying Multi-Select Picklists in SOQL

The INCLUDES and EXCLUDES operators are used to filter the multiselect picklist field. The multiselect picklist field in Salesforce allows the user to select more than one value from the list of values provided.

There are use-cases where we want to use a SOQL query and filter by multi-select picklist values. The picklist values can be specified with the AND/OR logic.

We use the Semicolon(;) and Comma(,) characters to add filter values to multi-select picklist fields. A semicolon is used as a special character to specify AND. A comma is used as a special character to specify OR.

Here is the example of filtering the multiselect picklist values. I’ve a custom object “Mobile__c” multiselect picklist field “Brand__c”. The values are in this field are Apple, Samsung, Nokia and HTC.

  • The below query filters on values in the Brand__c field that contains either of these values:
    Apple and Nokia selected.
Select Id, Name From Mobile__c Where Brand__c INCLUDES('Apple;Samsung');
  • The below query filters on values in the Brand__c field that contains either of these values:
    Apple and Samsung selected.
    HTC selected.
Select Id, Name From Mobile__c Where Brand__c INCLUDES('Apple;Samsung','HTC');
  • The below query filters on values in the Brand__c field that contains either of these values:
    Samsung selected.
    Nokia selected.
    HTC selected.
Select Id, Name From Mobile__c Where Brand__c INCLUDES('Samsung', 'Nokia','HTC');

How to Lock records using Apex in Salesforce?

Using UPDATE keyword in SOQL helps us to lock the records from being updating from another request.

Sample Code:

Account [] objAccts = [SELECT Id, Name FROM Account where Country='India' FOR UPDATE];

Note: We can’t use the ORDER BY keywords in any SOQL query that uses locking.

SOQL Query to Select All Fields of sObject

Sample Code:

public class DynamicSOQL {
  public static sObject getAllFieldsData(String objTypeName) {
        sObject sObj;
        Schema.DescribeSObjectResult[] descSObj = Schema.describeSObjects(new String[]{objTypeName});
        Map<String, Schema.SObjectField> fieldMap = descSObj[0].fields.getMap();
        List<String> fieldNames = new List<String>(fieldMap.keySet());
        system.debug('Fields-' + String.join(fieldNames, ','));
        String queryString = 'SELECT '+ String.join(fieldNames, ',') +' FROM '+ objTypeName +' LIMIT 1';
        sObj = Database.query(queryString);
        return sObj;
    }
}