How to Query all fields in Apex ( SELECT (ALL) * FROM SObject )

Hello Guys,

We have situations where we need to query all fields from any SObject in salesforce and because in SOQL we have to maintain resource allocation therefore we don't have option such as to query like SELECT * FROM SObjectName like we used to have in SQL.

So here is the utility method that you can use to fetch all field names for a particular SObject and return as string:

Method:

  public static String fetchFieldNames(String sObjectName){
      String SobjectApiName = sObjectName;
      Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
      Map<String, Schema.SObjectField> fieldMap = schemaMap.get(SobjectApiName).getDescribe().fields.getMap();
      String commaSepratedFields = '';
      for(String fieldName : fieldMap.keyset()){
          if(commaSepratedFields == null || commaSepratedFields == ''){
              commaSepratedFields = fieldName;
          }else{
              commaSepratedFields = commaSepratedFields + ', ' + fieldName;
          }
      }
      return commaSepratedFields;
  }

How to call method and use it:

        //calling fetchfieldNames() method to query all fields of Event object
        String sObjectName = 'CustomObject__C';
        String eventFields = fetchFieldNames(sObjectName);
        String query = 'SELECT ' + eventFields + ' FROM ' + sObjectName;
        System.debug('query string'+query);
        listOfSObject =  Database.query(query);
        System.debug('Records returned by query--> '+ listOfSObject);


Comments

Popular posts from this blog

List of Key Prefixes in Salesforce

SFDX Install CPQ in Scratch org