Dynamic SOQL query to fetch all fields in Salesforce

Dynamic SOQL query Salesforce

SOQL is Salesforce Object Query Language for querying data in the Force.com platform. It is very much similar to SQL.

But in SOQL, we can not query all fields from object. This statement is not allowed in SOQL:

select * from Account;

But there is one trick to query all fields of Object in SOQL query.

In the example below, we will use SOQL query to fetch all fields of account. We have added one ‘Fetch Account’ button on page. When we will click on this button all fields of account objects are fetched using SOQL query. We have also shown SOQL query in Visualforce page result.

Click for Demo

Visualforce Code:

<apex:page controller="selectAllSOQLExampleController" tabStyle="Account">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Fetch Accounts" action="{!fetch}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection columns="1" title="Dynamic SOQL Query" collapsible="false">
                <apex:outputText value="{!query}">
                </apex:outputText>
            </apex:pageBlockSection>

            <apex:pageBlockSection title="Account table" columns="1" collapsible="false">
                <apex:pageBlockTable value="{!accList}" var="acc">
                    <apex:column value="{!acc.name}"/>
                    <apex:column value="{!acc.phone}"/>
                    <apex:column value="{!acc.rating}"/>
                    <apex:column value="{!acc.industry}"/>
                    <apex:column value="{!acc.accountnumber}"/>
                </apex:pageBlockTable>

            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Code:

public class selectAllSOQLExampleController {
    public List<Account> accList{get;set;}
    public String query{get;set;}
    public selectAllSOQLExampleController(){
    }
    public PageReference fetch(){
        String SobjectApiName = 'Account';
        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;
            }
        }

        query = 'select ' + commaSepratedFields + ' from ' + SobjectApiName + ' Limit 5';

        accList = Database.query(query);

        return null;
    }
}

Permanent link to this article: http://www.sfdcpoint.com/salesforce/dynamic-soql-query-fetch-fields-object-salesforce/