Tag Archives: SOQL

Transaction Control using SavePoint and Rollback in Salesforce

SavePoint and Rollback will help us to maintain transaction for DML statement.
Suppose you  have written multiple lines of DML statements in a try block, If any error occurs during DML Operations, the operation will be rolled back to the most recent save point and the entire transaction will not be aborted.

Savepoint sp;
try{
   sp = Database.setSavepoint();
 
   Account a = new Account();
   a.Name = 'Test Account';
   insert a;
 
   Contact c = new Contact(Account = a.Id);
   c.FirstName = 'Biswajeet';
   c.LastName = 'Samal';
   insert c;
  }
catch(Exception e){
    Database.RollBack(sp);
}

In this example, if any error occurs while inserting the Account ‘a’ or Contact ‘c’, then the entire transaction will be rolled back to SavePoint ‘sp’, as specified in the catch section by Database.Rollback method.

toLabel() function in SOQL

  • toLabel() is used to convert the results of a field into user’s language.
  • toLabel() can convert the results into user’s language, if the translation workbench is enabled.
  • In all Salesforce edition we can use toLabel().
  • For picklist and Record type values we can use the toLabel() function in SOQL.

Here is an example:

SELECT Name, toLabel(Industry) FROM Account

Result:

download (1)

Not Like Operator in SOQL

Sometimes we need “NOT LIKE” operator in SOQL.
But SOQL will not allow someone to write simple query using “Not Like” operator such as:

SELECT Name From Account Where Name Not Like '%Test%';

So, here is the solution:

SELECT Name From Account Where Not Name Like '%Test%';

If you are using “GROUP By” clause with “Not Like” operator, here is an example:

SELECT Name From Account Where Not Name Like '%Test%' Group By Name;

SCOPE clasue in SOQL

The new USING SCOPE clause for SOQL queries lets you limit results by filterScope.

SELECT column_name FROM table_name USING SCOPE filterScope_value

filterScope_value can take one of the following enumeration values:

  • Everything – All records, for example All Opportunities.
  • Mine – Records owned by the user running the list view, for example My Opportunities.
  • Queue – Records assigned to a queue.
  • Delegated – Records delegated to another user for action: for example, a delegated task. This option is available in API version 17.0 and later.
  • MyTerritory – Records in the territory of the user seeing the list view. This option is available if territory management is enabled for your organization. This option is available in API version 17.0 and later.
  • MyTeamTerritory – Records in the territory of the team of the user seeing the list view. This option is available if territory management is enabled for your organization. This option is available in API version 17.0 and later.
  • Team – Records assigned to a team. This option is available in API version 17.0 and later.

Here is an example:

SELECT Name FROM Account USING SCOPE Mine