Mytutorialrack

How to retrieve all fields in SOQL query_

In this blog post, we will learn about a special trick to retrieve all the fields through SOQL query. If you are coming from a Java background or .NET background you must be familiar with this query:
“Select * from Table_name” : You can use this query in Java,.NET or PHP to retrieve all the data from a given table. But this feature is not available in case of SOQL query. We have to specify the column names  in the case of SOQL query. So in this blog post, I have shared a workaround which will retrieve all the fields in SOQL.

//The object from which we need to query data. We are retrieve the field map and storing in the map variable
Map <String, Schema.SObjectField> mapObjField = Account.sObjectType.getDescribe().fields.getMap();
String strfieldName = ''; //empty string to store the field names
for(Schema.SObjectField field : mapObjField.Values())
{
Schema.DescribeFieldResult fieldRes = field.getDescribe();
strfieldName += fieldRes.getName() + ',';
}
strfieldName = strfieldName.substring(0, strfieldName.length()-1);
// Build a Dynamic Query String.
List <Opportunity> OppList = Database.query('select ' + strfieldName + ' from Opportunity');

This blog post is using the getMap() method from here:  https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/

Share:

Recent Posts