function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sathishsfdcsathishsfdc 

custom settings filter value using soql

I have a custom setting:
Country__c  with  checkbox fields called  city__c   and 1 normal field.
now my crietra is to fetch the values inside the custom setting only when  city__c checkbox is checked to true. 
now normally:
 
List<Country__c> country = [Select Name from Country__c where City__c = true ];
List<String> fields = new List<String>();
for(Country__c field : country) {
   fields.add(country.name);
}
System.debug(fields);
This works in workbench but i cannot reproduce the same in apex class. i am not able to do  an soql query with filter condition on the apex class.is there any other alternative???
 
Best Answer chosen by sathishsfdc
RAM AnisettiRAM Anisetti
Try this one
 
List<String> fields = new List<String>();
for(Country__c ct:Country__c.getall().values()){
  if(ct.City__c ==true){
    fields.add(ct.name);
  }
}

 

All Answers

RAM AnisettiRAM Anisetti
Try this one
 
List<String> fields = new List<String>();
for(Country__c ct:Country__c.getall().values()){
  if(ct.City__c ==true){
    fields.add(ct.name);
  }
}

 
This was selected as the best answer
Arun Deepan LJArun Deepan LJ
Hi sathish,

There is a trade off between using the SOQL and getAll().values(), that depends on how many values are there. 
If you are looping over the map values() searching for a single record based on a field other than the Name then SOQL would probably serve you better as you could just grab the required records.

One thing to note with the SOQL approach. It will cost you one of your 100 synchronous SOQL queries governor limit. Where as the cached getAll() is free from that but may not have the absolute latest data.

If you can access the Map by the Name key then the Map has some good advantages over SOQL if you need to pick out several values. Even better would be pulling out individual CustomSetting__c records by name using getInstance(dataset_name)

So, in conclusion, it depends on how many of those list custom setting values you want and if you can access them by name. You will need to try both approaches on your data to see which works best while taking into account if you can spare the extra SOQL query.