Dynamic SOQL query to fetch all fields of Sobject

by Rijwan Mohmmed
dynamic-soql-query-to-fetch-all-fields-of-sobject-techdicer

Hello Friends, today I am going to show you an example that explains how to fetch all fields of any sObject using dynamic SOQL Query in Apex.

In many scenarios you have to get all fields of the sobject, when a large number of fields are available of an object, it’s tough to query fields one by one in the Apex Class.

Also Check this: Sharing records by Apex in Salesforce

Highlights Points :

  1. Dynamic SOQL refers to the creation of a SOQL string at run time with Apex code.
  2. Use Database.query(stringQuery); for query.
  3. No need to cast from a generic sObject to a concrete sObject.
  4. Have the same governor limits as static queries.

Example :

Here we will query account all fields and debug the data

DyanmicQueryDataCtrl.cls :

public class DyanmicQueryDataCtrl {
	
    public static void DyanmicQueryMethod(){
        Set<String> SobjectFields = Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap().keySet();    
        List<String> fieldsInList = new List<String>(SobjectFields);
        List<Account> accList = Database.query('SELECT ' + String.join(fieldsInList, ',') + ' FROM Account');
        System.debug('accList '+accList);
    }
}
dynamic-soql-query-to-fetch-all-fields-of-sobjects-techdicer
dynamic-soql-query-to-fetch-all-fields-of-sobject-techdicer

DyanmicQuerySearchTextCtrl.cls: In this example, we are searching text in dynamic SOQL Query.

public class DyanmicQuerySearchTextCtrl {
    
    public static void DyanmicQuerySearchTextMethod(){
        String query = 'SELECT Id, Name FROM Account WHERE Type = \'Customer - Direct\' LIMIT 1';
        Account acc = Database.query(query);
        System.debug('acc data=> '+ acc);
    }
}
 dynamic-soql-query-to-fetch-all-fields-of-sobject-search-text-techdicer
dynamic-soql-query-to-fetch-all-fields-of-sobjects-search-text-techdicer

Reference :

  1. Dynamic SOQL
What’s your Reaction?
+1
0
+1
0
+1
0
+1
1
+1
2
+1
0

You may also like

Leave a Comment