Thursday, 2 February 2012

Using Apex Variables in SOQL and SOSL Queries

This post will helps us to manage queries shorter and effective:

Account A = new Account(Name='xxx');
insert A;
Account B;

// A simple bind 
    
B = [SELECT Id FROM Account WHERE Id = :A.Id];

// A bind with arithmetic 
    
B = [SELECT Id FROM Account 
     WHERE Name = :('x' + 'xx')];

String s = 'XXX';

// A bind with expressions 
    
B = [SELECT Id FROM Account 
     WHERE Name = :'XXXX'.substring(0,3)];

// A bind with an expression that is itself a query result 
    
B = [SELECT Id FROM Account
     WHERE Name = :[SELECT Name FROM Account
                    WHERE Id = :A.Id].Name];

Contact C = new Contact(LastName='xxx', AccountId=A.Id);
insert new Contact[]{C, new Contact(LastName='yyy', 
                                    accountId=A.id)};

// Binds in both the parent and aggregate queries 
    
B = [SELECT Id, (SELECT Id FROM Contacts
                 WHERE Id = :C.Id)
     FROM Account
     WHERE Id = :A.Id];

// One contact returned 
    
Contact D = B.Contacts;

// A limit bind 
    
Integer i = 1;
B = [SELECT Id FROM Account LIMIT :i];

// An IN-bind with an Id list. Note that a list of sObjects 
    
// can also be used--the Ids of the objects are used for  
    
// the bind 
    
Contact[] cc = [SELECT Id FROM Contact LIMIT 2];
Task[] tt = [SELECT Id FROM Task WHERE WhoId IN :cc];

// An IN-bind with a String list 
    
String[] ss = new String[]{'a', 'b'};
Account[] aa = [SELECT Id FROM Account 
                WHERE AccountNumber IN :ss];

No comments:

Post a Comment