Database.query(query) returns sobjects.

I want to access each fields in this sobject to check the value on each field.

How is this done in controller?

  • 2
    Can you post the tried out code so far?
    – highfive
    Sep 25, 2014 at 4:28

2 Answers 2


Since Database.query returns a List<SObject> you'll want to cast the result before you use it to access any fields. Once you've done that you can access the fields like you normally would.

List<Account> accounts = (List<Account>)Database.query(...);

// You can do the cast directly in the loop declaration, but I've not done so here for clarity
for(Account a : accounts)
    // Do something with your Accounts

You can access the fields without casting by using get(String) and getSObject(Schema.SObjectField), but I wouldn't recommend using them unless you need the dynamic behaviour. By using the dynamic methods you lose all the type-safety features that Force.com provides.


Database.query(query) returns a list of SOBJECT . So loop through the SObject using :

for(SObject s : LstSObjects ) {
//access each field values here using s.
//example as follows 
s.Name = 'ABC';


Use a list to manipulate or calculate values on Fields in SOBJECT .

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .