How to Select All Fields with SOQL in Apex

How to Select All Fields with SOQL in Apex

// Based on Record ID , fetch all the field particular object

ID recordId = '01t90000000vQFw';
DescribeSObjectResult describeResult = recordId.getSObjectType().getDescribe();
List<String> fieldNames = new List<String>( describeResult.fields.getMap().keySet() );
System.debug( fieldNames);
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 );


// Based on Object without an ID, simply specify the object to then derive the sobject type
    DescribeSObjectResult describeResult = SobjectApiName.getSObjectType().getDescribe();
List<String> fieldNames = new List<String>( describeResult.fields.getMap().keySet() );
System.debug(fieldNames);
String query = ' SELECT ' + String.join( fieldNames, ',' ) +' FROM ' + describeResult.getName();
// to return generic list of sobjects or typecast to expected type
List<SObject> records = Database.query( query );
System.debug( records );
System.debug( records.size());

Comments

Popular posts from this blog

Salesforce Spring 16 Release Exam (Maintenance Exam Q&A) for Developer 201 Admin

Show Hyper Link On Add Error in Salesforce Trigger

Show the Success Message before Redirecting the Detail page on Visualforce Page