Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Salesforce SOQL describe table

Is there a way to fetch a list of all fields in a table in Salesforce? DESCRIBE myTable doesn't work, and SELECT * FROM myTable doesn't work.

like image 418
Maverick Avatar asked Sep 25 '12 15:09

Maverick


People also ask

Can I do select * In SOQL?

Thanks. No, you can't do this in SOQL, but you can generate dynamically your SOQL query with the list of all fields (Id, Name, etc...).

What does =: mean in SOQL?

=: symbol is used inside the SOQL query to comapre a condition with an external object/variable that already define.


1 Answers

From within Apex, you can get this by running the following Apex code snippet. If your table/object is named MyObject__c, then this will give you a Set of the API names of all fields on that object that you have access to (this is important --- even as a System Administrator, if certain fields on your table/object are not visible through Field Level Security to you, they will not show up here):

// Get a map of all fields available to you on the MyObject__c table/object
// keyed by the API name of each field
Map<String,Schema.SObjectField> myObjectFields 
   = MyObject__c.SObjectType.getDescribe().fields.getMap();

// Get a Set of the field names
Set<String> myObjectFieldAPINames = myObjectFields.keyset();

// Print out the names to the debug log
 String allFields = 'ALL ACCESSIBLE FIELDS on MyObject__c:\n\n';
for (String s : myObjectFieldAPINames) {
    allFields += s + '\n';
}
System.debug(allFields);

To finish this off, and achieve SELECT * FROM MYTABLE functionality, you would need to construct a dynamic SOQL query using these fields:

List<String> fieldsList = new List<String>(myObjectFieldAPINames);
String query = 'SELECT ';
// Add in all but the last field, comma-separated
for (Integer i = 0; i < fieldsList.size()-1; i++) {
   query += fieldsList + ',';
}
// Add in the final field
query += fieldsList[fieldsList.size()-1];
// Complete the query
query += ' FROM MyCustomObject__c';
// Perform the query (perform the SELECT *)
List<SObject> results = Database.query(query);
like image 128
zachelrath Avatar answered Sep 28 '22 09:09

zachelrath