If you worked with SQL or any other query language before, you probably familiar with Select * from …, right? This is the way to fetch all fields from a particular table in other(mostly all) query languages. But in the Salesforce world, we were not having this feature. In SOQL, there is nothing with which we can fetch all the fields unless we specifically mention all the field names in the query.

But now in Spring 21, Salesforce is bringing a function through which we can fetch all fields in SOQL Query.

We have now FIELDS(ALL), FIELDS(STANDARD), and FIELDS(CUSTOM) which we can use in the SOQL query.

  • FIELDS(ALL) – This fetches all the fields of an object. This is similar like Select * from SQL.
  • FIELDS(STANDARD) – This fetches all standard fields of an object.
  • FIELDS(CUSTOM) – This fetches all custom fields of an object.
Here is how the query will look like –

List<Contact> allConatcts = [SELECT FIELDS(ALL) FROM CONTACT LIMIT 200];

In Subqueries, it will look like –
List<Account> allAccounts = [
SELECT Account.Name, (SELECT FIELDS(ALL) FROM Account.Contacts LIMIT 200)
FROM Account
];

BOUNDED AND UNBOUNDED QUERIES

When API cannot determine the set of fields in advance, then it will consider query as Unbounded Query, other if API can determine the set of fields in advance, then it is Bounded Query. For example – The number of custom fields for an object is not pre-determined, so FIELDS(CUSTOM) and FIELDS(ALL) are considered as Unbounded Query. The below table is a good reference to understand how these functions will work w.r.t bounded and unbounded queries.

LIMITATION

With great power, comes responsibilities. In Multi-tenant architecture, it is very much important to make sure running queries for one org will not have any impact on that org as well as other orgs present in the same server/node. As a result,
  • Fetching more than 200 records per query is not allowed.
Note – If you want to understand the performance of SOQL query, you should use the Query Plan tool. Here is my earlier post explaining how you can use this tool –

BEST PRACTICE

If field names can be determined during runtime (through describe or metadata or custom settings etc.), then adding the field names in the query will give you better performance than using the function FIELDS function. The below post will help you to understand how you can build your queries dynamically.