Wednesday, July 20, 2016

Apex Basics & Database Writing SOQL Queries

Note: All credit goes to Salesforce, I am just a developer who enjoy playing trailhead and try to make note to myself.

Querying Related Records

Get child records related to parent record

Account[] acctsWithContacts = [SELECT Name, (SELECT FirstName,LastName FROM Contacts)
                               FROM Account 
                               WHERE Name = 'SFDC Computing'];
// Get child records
Contact[] cts = acctsWithContacts[0].Contacts;
System.debug('Name of first associated contact: ' 
             + cts[0].FirstName + ', ' + cts[0].LastName);

Querying Record in Batches By Using SOQL For Loops

With a SOQL for loop, you can include a SOQL query within a for loop. The results of a SOQL query can be iterated over within the loop. SOQL for loops use a different method for retrieving records—records are retrieved using efficient chunking with calls to the query and queryMore methods of the SOAP API. By using SOQL for loops, you can avoid hitting the heap size limit.

SOQL for loops iterate over all of the sObject records returned by a SOQL query. The syntax of a SOQL for loop is either:


for (variable : [soql_query]) {
    code_block
}

OR


for (variable_list : [soql_query]) {
    code_block
}

It is preferable to use the sObject list format of the SOQL for loop as the loop executes once for each batch of 200 sObjects. Doing so enables you to work on batches of records and perform DML operations in batch, which helps avoid reaching governor limits.


insert new Account[]{new Account(Name = 'for loop 1'), 
                     new Account(Name = 'for loop 2'), 
                     new Account(Name = 'for loop 3')};

// The sObject list format executes the for loop once per returned batch
// of records
Integer i=0;
Integer j=0;
for (Account[] tmp : [SELECT Id FROM Account WHERE Name LIKE 'for loop _']) {
    j = tmp.size();
    i++;
}
System.assertEquals(3, j); // The list should have contained the three accounts
                       // named 'yyy'
System.assertEquals(1, i); // Since a single batch can hold up to 200 records and,
                       // only three records should have been returned, the 
                       // loop should have executed only once

Challenge solution that I wrote



public class ContactSearch {
    
    public static List<Contact> searchForContacts(String lastName,String postalCode){
        
        try{
            List<Contact> lstContact=[Select Id,Name from Contact where LastName =:lastName and MailingPostalCode=:postalCode];
            return lstContact;
        }
        catch(Exception e){
            return null;
        }
        
    }

}

 Salesforce trailhead

No comments:

Post a Comment