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

Fetch Picklist value in LWC using Schema class

Get Last day of Month

Write The Dynamic Query in Salesforce and bind in page block table with filter conditions