Salesforce | Select * in SOQL and dynamic queries

|
| By Webner

Execute dynamic query in salesforce. Also retrieve all fields from salesforce object without writing fields names in query.

Solution: In Salesforce we can’t write as Select * from object. We have to mention the field specific field name to query data. Also there are situations when we need to make dynamic query on any object. For this you can create a function with code like below:

String objName= 'Account'; //Any object name you want to pass 
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Map<String, Schema.SObjectField> fieldMap = schemaMap.get(objName).getDescribe().fields.getMap();
String fields= '';
for(String fieldName : fieldMap.keyset()){
if(fields == null || fields== ''){
fields= fieldName;
}else{
fields= fields+ ', ' + fieldName;
}
}
String query = 'select ' + fields+ ' from ' + objName+ ' Limit 5';
List objList= Database.query(query);
system.debug(objList);

Leave a Reply

Your email address will not be published. Required fields are marked *