Accueil > Conseils > Save some SOQL queries with the Spring ’21 new Custom Metadata Static Methods

Save some SOQL queries with the Spring ’21 new Custom Metadata Static Methods

 2 minutes de lecture


avril 7, 2021


EDIT: Despite the exciting title, I stand corrected: Even when Custom Metadata records are retrieved with SOQL Queries, these are not included in the governor limit as documented here: “custom metadata records can have unlimited SOQL queries”. Thank you to everyone that came to me to let me know.

We all have this kind of project where some part of the application is close to the limit of allowed SOQL queries. Spring ’21 brings us a simple and easy way to remove some of them, let’s take a look.

Getting Custom Metadata records

Using Custom Metadata Types is a great way to store configuration information for your app that can be configured and deployed easily by an administrator.

Using it in your code requires you to retrieve this information. And today the way to do it is just to query the Custom Metadata records like you would do for any regular sObject:

This is very easy to do, with only one drawback: it consumes one SOQL, which we all know are limited.

Getting Custom Metadata records… starting Spring ‘21

Spring ’21 Release Notes are a beast of 617 pages, full of great updates. But you can’t miss this one: You can now access Custom Metadata Type records using static methods, ie. without using any SOQL query.

It’s now as easy as this:

Notice that you don’t even have to specify the fields you need !

Also, as Custom Metadata Types are now part of the application cache, these methods should be faster than their SOQL counterpart.

Several methods are available to get the Custom Metadata records you need: getAll(), getInstance(recordId), getInstance(qualifiedApiName), and getInstance(developerName. All of them are documented in the Apex Developer Guide.

That’s it ! As you can see, there are no drawback on this update, it’s just a better way to get Custom Metadata records. So just stop using SOQL queries for this, and update your existing code to benefit from these new methods !

Would you want to know more on the other updates made to SOQL and Custom Metadata Types in Spring ’21, have a look to Nesrine Ould Braham’s blog post here.