Thursday, November 21, 2013

Like Operator in SOQL Query

Like Operator:

        Like Operator in SOQL act as a Comparison operator  for String Field Expression.Expression is true if the value in the specified fieldName matches the characters of the text string in the specified value. It provides a mechanism for matching partial text strings and includes support for wildcards.


Notes:

  • The % and _ wildcards are supported for the LIKE operator.
  • The % wildcard matches zero or more characters.
  • The _ wildcard matches exactly one character.
  • The text string in the specified value must be enclosed in single quotes.
  • The LIKE operator is supported for string fields only.
  • The LIKE operator performs a case-insensitive match, unlike the case-sensitive matching in SQL.
  • The LIKE operator in SOQL and SOSL supports escaping of special characters % or _.
  • Do not use the backslash character in a search except to escape a special character.
Special Characters % and _

   %-->Specifies that Zero ,One or more characters 
   _ --> Specifies that only One character.

SOQL Query Examples for Like Operator

Example, the following query matches Appleton, Apple, and Bappl , but not Appl:

   SELECT Id, Name FROM Widget__c WHERE Name LIKE 'appl_%'

Example 1:Withou Using Variable

     1.[Select Id,FirstName form User where FirstName LIKE 'srinivas'];

     2.[Select Id,FirstName form User where FirstName LIKE '%srinivas'];

     3.[Select Id,FirstName form User where FirstName LIKE '%srinivas_'];

Example 2:Like Using Variable need to use (:) bind Variavble

    User object contains FirstName as below Records:
     1. srinivasa
     2. msrinivasa
     3. srinivas

   String firstname ='srinivas';

 User u=  [SELECT Id , FirstName,LastName  FROM User where FirstName LIKE : firstName LIMIT 9];

  This query returns Users record from User object where FirstName of user is srinivas only.
  output: srinivas record only number3

Example 2:Using variable with % and _ wildcard characters
  String firstname ='srinivas';
  String str='%'+firstname +'%';
 User u=  [SELECT Id , FirstName,LastName  FROM User where FirstName LIKE : firstName LIMIT 9];

This query will return Users record from User object where FirstName of User contains srinivas
output:It returns Three Records  1. srinivasa 2. msrinivasa 3. srinivas

                              
                                                         
                               


No comments:

Post a Comment