Tuesday, October 31, 2017

How to Select All Fields with SOQL in Apex

1. Query All Fields for a Known Record ID:

ID recordId = '5001a00000CgCE2';

DescribeSObjectResult describeResult = recordId.getSObjectType().getDescribe();

List<String> fieldNames = new List<String>( describeResult.fields.getMap().keySet() );

String query =
  ' SELECT ' +
      String.join( fieldNames, ',' ) +
  ' FROM ' +
      describeResult.getName() +
  ' WHERE ' +
      ' id = :recordId ' +
  ' LIMIT 1 '
;

// return generic list of sobjects or typecast to expected type
List<SObject> records = Database.query( query );

System.debug( records );

2. Query All Fields for All Records

The same concept as above but we don’t have a specific record ID, so we need to determine the sobjectype by explicitly specifying the object we’ll query on.

// without an ID, simply specify the object to then derive the sobject type
DescribeSObjectResult describeResult = Account.getSObjectType().getDescribe();

List<String> fieldNames = new List<String>( describeResult.fields.getMap().keySet() );

String query =
  ' SELECT ' +
      String.join( fieldNames, ',' ) +
  ' FROM ' +
      describeResult.getName()
;

// return generic list of sobjects or typecast to expected type
List<SObject> records = Database.query( query );

System.debug( records );

No comments:

Post a Comment