Hello Everyone, In this post, I am going to show you an example that explains how to get all fields of any sObject using dynamic SOQL in apex. In many scenario you have to get all fields of sobject, when a huge amount of fields are available of object, it's tough to query fields one by one in the apex handler. To make easier this task you can go through this exciting post. So let's begin

Dynamic SOQL to fetch all fields of Sobject

The following code snippet working well with any object of salesforce, here i am fetching "Opportunity" object fields.

 Set<String> SobjectFields = Schema.getGlobalDescribe().get('Opportunity').getDescribe().fields.getMap().keySet();        
List<Opportunity> lstOpp=Database.query('SELECT ' + String.join(new List<String>(SobjectFields), ',') + ' FROM Opportunity');
System.debug('lstOpp '+lstOpp);

Output:

To get data with specific id, you can use "Where" clause in above dynamic query.
 String OppId='0060K00000Tw24r'; // replace with your opportunity id
Set<String> SobjectFields = Schema.getGlobalDescribe().get('Opportunity').getDescribe().fields.getMap().keySet();
List<Opportunity> lstOpp = Database.query('SELECT ' + String.join(new List<String>(SobjectFields), ',') + ' FROM Opportunity WHERE Id = \'' + OppId + '\'');
System.debug('lstOpp '+lstOpp);

Custom objects are also supported above dynamic query.

Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.

Thank you.