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 Post

Show Hyper Link On Add Error in Salesforce Trigger

Select and Deselect Check Box on Page Block Table in Visual force Using JavaScript

Send SMS Using Batch Class in Salesforce