salesforce SOQL : query to fetch all the fields on the entity

Sukhhhh picture Sukhhhh · Jan 8, 2012 · Viewed 39k times · Source

I was going through the SOQL documentation , but couldn't find query to fetch all the field data of an entity say , Account , like

select * from Account [ SQL syntax ]

Is there a syntax like the above in SOQL to fetch all the data of account , or the only way is to list all the fields ( though there are lot of fields to be queried )

Answer

Adam picture Adam · Jan 9, 2012

Create a map like this:

Map<String, Schema.SObjectField> fldObjMap = schema.SObjectType.Account.fields.getMap();
List<Schema.SObjectField> fldObjMapValues = fldObjMap.values();

Then you can iterate through fldObjMapValues to create a SOQL query string:

String theQuery = 'SELECT ';
for(Schema.SObjectField s : fldObjMapValues)
{
   String theLabel = s.getDescribe().getLabel(); // Perhaps store this in another map
   String theName = s.getDescribe().getName();
   String theType = s.getDescribe().getType(); // Perhaps store this in another map

   // Continue building your dynamic query string
   theQuery += theName + ',';
}

// Trim last comma
theQuery = theQuery.subString(0, theQuery.length() - 1);

// Finalize query string
theQuery += ' FROM Account WHERE ... AND ... LIMIT ...';

// Make your dynamic call
Account[] accounts = Database.query(theQuery);

superfell is correct, there is no way to directly do a SELECT *. However, this little code recipe will work (well, I haven't tested it but I think it looks ok). Understandably Force.com wants a multi-tenant architecture where resources are only provisioned as explicitly needed - not easily by doing SELECT * when usually only a subset of fields are actually needed.