Salesforce Cookies #10

Creating a dynamic SOQL which includes all the fields

I have seen this question several times on developer forums and I thought it could be another addition to Salesforce cookies. If you are wondering how can you query all the fields of an object then you can use the following code snippet.

Map<String,Schema.SObjectField> mapFields = Account.getSObjectType().getDescribe().fields.getMap(); 
List<String> fieldNames = new List<String>();
for( String fieldName : mapFields.keySet() ) {
     fieldNames.add( fieldName );
     // For relationship fields
     if( Schema.DisplayType.Reference == mapFields.get(fieldName).getDescribe().getType() )
     fieldNames.add( mapFields.get(fieldName).getDescribe().getRelationshipName() + '.Name' ); 
String query = 
    ' SELECT ' + 
    String.join( fieldNames, ',' ) + 
    ' FROM Account ' +
    ' WHERE ' + 
    ' Id = :recorId ';
List<Account> lstRecords = Database.query( query );

This is quite similar to SQL query which uses wildcard characters – SELECT * FROM Table.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s