Salesforce SOQL describe table
Asked Answered
H

4

16

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.

Haemolysin answered 25/9, 2012 at 15:23 Comment(0)
T
14

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);
Tauto answered 25/9, 2012 at 17:22 Comment(0)
S
3

the describeSObject API call returns all the metadata about a given object/table including its fields. Its available in the SOAP, REST & Apex APIs.

Slavin answered 25/9, 2012 at 16:37 Comment(0)
E
1

Try using Schema.FieldSet

Schema.DescribeSObjectResult d =   Account.sObjectType.getDescribe();
Map<String, Schema.FieldSet> FsMap = d.fieldSets.getMap();

complete documentation

Eupepsia answered 25/9, 2012 at 16:37 Comment(3)
How would I query this with SOQL though?Haemolysin
I think it is not possible using only SOQL... you can do that using Javascript (or any API implementation language), or Apex as I answered .Eupepsia
You can see your same question and the same answer here: #8780913Eupepsia
C
-8

Have you tried DESC myTable?

For me it works fine, it's also in the underlying tips in italic. Look:

enter image description here

Cotillion answered 23/8, 2014 at 15:4 Comment(1)
[sf:MALFORMED_QUERY] MALFORMED_QUERY: unexpected token: DESCUnitive

© 2022 - 2024 — McMap. All rights reserved.