I have a custom metadata sObject - I want to retrieve all the field values into a set.

Health_Cloud_Case_Integration_Settings__mdt cmdtRecords = [SELECT Id, Field1, Field2, etc FROM Health_Cloud_Case_Integration_Settings__mdt LIMIT 1];

Please note that the query is dynamic, so might contain fields I don't necessarily know at compile time.

So I want the value of Field1, Field2, Field3 into a set. Sort of like getall().values() for settings?

Full code below:

String MDTQueryString = 'SELECT '+ String.join(new List<String>(integrationCaseFields), ', ') + ' FROM ' + 'Health_Cloud_Case_Integration_Settings__mdt LIMIT 1';

List<Health_Cloud_Case_Integration_Settings__mdt> cmdtRecords = database.query(MDTQueryString);

Health_Cloud_Case_Integration_Settings__mdt cmdtRecord = cmdtRecords[0];
// Set<String> fieldValues = cmdtRecord field values
  • Can you loop through the results of that query and add them to a set? More context on what you want to do with the resulting set might help. May 1, 2020 at 16:07
  • Hi, it's a dynamic query so not sure if it would work. Updated OP with my full code May 1, 2020 at 16:20
  • Do you mean to say you want all the values from all the fields in a single set, or all the values from each field in different sets, or all the records deduplicated in to a set?
    – sfdcfox
    May 1, 2020 at 16:25
  • @sfdcfox Option #1 please. May 1, 2020 at 16:27
  • 1
    Derek's answer was correct, I just added a code example to get you started.
    – sfdcfox
    May 1, 2020 at 16:33

1 Answer 1


Probably the simplest way is to make use of getPopulatedFieldsAsMap() (method provided on SObjects, which is guess custom metadata types also fall under).

As the name suggests, the fields that you query get returned as a Map<String, Object>. From there, you could call .values() to get a List<Object>, and feed that into a set.

// Query records and strip out Id and audit fields //
List<Health_Cloud_Case_Integration_Settings__mdt> cmdtRecords = database.query(MDTQueryString).deepClone(false, false, false);
// A place to store the values //
Set<Object> values = new Set<Object>();
// Grab all populated values and put them in the Set //
for(sObject record: cmdtRecords) {
  • I hope you don't mind, but I added a code example so as to not duplicate your answer.
    – sfdcfox
    May 1, 2020 at 16:32
  • Thank you both. Is it possible to return the values set as a set of string? May 1, 2020 at 16:39
  • nevermind, I just looped through and done .toString(). Thanks again May 1, 2020 at 16:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .