Saturday, May 21, 2022

FIELDS() function in Salesforce

SOQL SELECT statement (for example, SELECT Id, Name FROM Account) can be complicated if you need to retrieve many fields and if you don’t know what fields an object has, you must first get a descriptionof the object. Typically, you use a call to first get a description of the object, then parse the description to identify the fields. Then you construct a SOQL query that specifies the fields, and then make another call to submit the query. 

In order to avoid all of the complexity mentioned above we can use  FIELDS() function which simplifies SELECT statements, avoids the need for multiple API calls, and provides a low-code method to explore the data in your org.

The FIELDS() function lets you select groups of fields without knowing their names in advance. 

You can now include any of these in the field list:


FIELDS(ALL)—to select all the fields of an object.

FIELDS(CUSTOM)—to select all the custom fields of an object.

FIELDS(STANDARD)—to select all the standard fields of an object.

In each case, FIELDS() respects field-level security so it only shows the fields that you have permission to access.


Examples:


SELECT FIELDS(ALL) FROM Account LIMIT 200

SELECT FIELDS(CUSTOM) FROM Account LIMIT 200

SELECT FIELDS(STANDARD) FROM Account


We can also mix FIELDS() with other field names in the field list. For example:


SELECT Name, Id, FIELDS(CUSTOM) FROM Account LIMIT 200

SELECT someCustomField__c, FIELDS(STANDARD) FROM Account


FIELDS() can also be used in subqueries. 


For example:


SELECT

   Account.Name, 

   (SELECT FIELDS(ALL) FROM Account.Contacts LIMIT 200)

FROM Account


We can also use FIELDS() with /query in REST API as shown below:

GET https://yourInstance.salesforce.com/services/data/v54.0/query?​q=SELECT+FIELDS(STANDARD)+FROM+Account

Note: 

If you already know which fields you want to retrieve, you’ll get better performance by specifying them explicitly 

rather than using FIELDS() and retrieving more fields than you need.


No comments:

Post a Comment