How to get the value of a key in a Salesforce sObject

Published May 4th 2018

Let's say you run a SOQL query to pull out the name of an account within a Salesforce trigger. You've written a SOQL that retrieves an account based on the ID of the object that fired the trigger. Something like:

[SELECT Name FROM Account WHERE Id='ACCOUNTNUMBERHERE']

Your account number is likely being generated dynamically. In my case, it was being generated from a linked Account object as part of a custom object. Anyway, that's besides the point for the scope of this particular post.

That SOQL will return something similar to:

Account: {Name=Joe Bloggs, Id=1234ABCD56EF7G9Z}

In order to get the value of Name, assign the query to a variable. In the case of an account, you could use Account, but to keep this as open as possible, I'm going to use the generic sObject type. Once you've assigned the returned array, you'd simply use the method .get() on the variable with the desired key you want to retrieve the value of.

For example:

// Define the variable acct and assign the returned value of the SOQL query to it.
sObject acct = [SELECT Name FROM Account WHERE Id='ACCOUNTNUMBERHERE'];

// Use the .get() method to get the name of the account.
String acctName = acct.get('Name');

// Log it out so we can see it's being returned correctly.
system.debug(acctName);

You'd follow this patter for whatever the key was. So say your query called a custom field on an account object called Example Field in addition to the Account Name, you'd use a similar SOQL query:

[SELECT Name, Example_Field__c FROM Account WHERE Id='ACCOUNTNUMBERHERE']

You would then use the method .get() like so:

yourVariable.get('Example_Field__c');