+ Start a Discussion

Getting field names from query result

Hi all,


From the below query, I want to get the field names provided in the query from the result 'obj' dynamically.


sObject obj =[Select id,  Owner, Additional_Info__c, Replacement_Info__c, Phone, Mobile__c,Comments__c from Account where ID =:ID];




Well can you explain a lil bit more ?
You doesnt seem to generate the SOQL dynamically and seems like while querying you are aware about the fields which should be present.

To get the field values Dynamically you need to do something like this

Thanks for your reply Avi!


Actually we get the query as a parameter for a method, within the method we will execute the query using database.query(QueryString); 


Now, we want to get the FieldApiNames from the query result.



You can modify the method to accept a list of fields, this way you will be able to get the api name and the query as well


if I am not wrong you want to fetch list of field name on any object. you can do it by applying describe method on object. as below : 


Map <String, Schema.SObjectField> fieldMap = schemaMap.get(selectedObject).getDescribe().fields.getMap();

Here fieldMap.Values() is list of field you can get field name and label as below

for(Schema.SObjectField sfield : fieldMap.Values())

system.debug( sfield.getDescribe().getLabel()+'========'+ sfield.getDescribe().getName());



Sanjay Bhati 95Sanjay Bhati 95
Hi shylaja,

I know it too late but check it once.
I think you want to get all the field that is used in soql. Please have a look on below code.
Account acc = [select Id,Name from Account where id=:a.Id];
Map<String, Object> fieldsToValue = acc.getPopulatedFieldsAsMap();
for (String fieldName : fieldsToValue.keySet()){
     System.debug('field name is ' + fieldName + ', value is ' + fieldsToValue.get(fieldName));
//getPopulatedFieldsAsMap this method will return the map of field and value that is used in soql query only.

I hope this solution will work for you. Let me know if you have any doubt.