Query SObject without burning SOQL queries

When you are writing Apex code you want to minimize the amount of SOQL queries in your code. One of the ways todo this is to create an SObject with some information of that object.

Let us say you have the following SOQL query:

Contact getAccountId = [Select AccountId from Contact limit 1];

Now you would like more information about the Account for that contact, you where thinking of taking the AccountId and running another SOQL query like this:

Account showAccountInfo = [Select Id from Account where Id=:getAccountId.AccountId];

You are burning unnecessary SOQL queries. You can do this following:

 Account showAccountInfo = new Account(Id=:getAccountId.AccountId);

You are not burning a SOQL query as you now have created an Object of that account. So you can do the following to query or update fields:

Get Information:

showAccountInfo.Name

Assign New Value:

showAccountInfo.Name='New Account Name'
update showAccountInfo;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: