Fields

SOQL Custom Metadata

Querying Custom Metadata

SOQL custom metadata queries retrieve configuration data.

Understanding Custom Metadata

Custom metadata types in Salesforce are used to store configuration data that can be used across your organization. Unlike custom objects, custom metadata allows you to create your own custom data types, define the fields, and set up records that can be queried using SOQL just like regular Salesforce objects.

Why Use SOQL for Custom Metadata?

SOQL (Salesforce Object Query Language) is a powerful tool for retrieving data from Salesforce databases. When querying custom metadata, SOQL allows you to:

  • Access configuration data easily without hardcoding values.
  • Ensure that your configurations are consistent across different environments.
  • Leverage the same querying capabilities as with other Salesforce objects.

Basic SOQL Query for Custom Metadata

To query custom metadata, you need the developer name of the custom metadata type. Here's a basic example:

In this example, MyCustomMetadataType__mdt is the API name of the custom metadata type. The query retrieves the DeveloperName and MasterLabel fields from all records of this metadata type.

Filtering Custom Metadata Records

Just like with other SOQL queries, you can filter custom metadata records using the WHERE clause. For instance:

This query filters the records to return only those with a DeveloperName of ExampleMetadata.

Using Custom Metadata in Apex

Custom metadata can be utilized within Apex code to dynamically access configuration data. Here’s how you can access custom metadata records in Apex:

The above example demonstrates how to retrieve and iterate over custom metadata records within an Apex class. This can be particularly useful for applications that need to adapt to different configurations without altering the codebase.

Best Practices for Custom Metadata Queries

  • Use Descriptive Names: Ensure your custom metadata types and fields have meaningful names for easier identification and maintenance.
  • Limit Query Scope: Use the WHERE clause to limit the records returned by your query to improve performance.
  • Leverage Caching: Custom metadata is cached at runtime, so frequent access will not impact performance as much as querying standard objects.

Fields