I have a Visualforce page that allows users to filter a list records based their filter criteria.

My issue is that I end up having to make a permutation for every possible combination of their selection. Imagine ten fields with three values (null,true, false)

This leads to a giant railroad yard of if statement logic blocks and queries. As more fields are added or requested to be filtered by.... this gets out of hand.

There has to be a better way to write this.


public boolean gender {get; set;}
public boolean veteran {get; set;}
public boolean disabled {get; set;}
public boolean hispanic {get; set;}
public boolean felon {get; set;}
public boolean balding {get; set;}
public boolean fat ...... etc...

if(gender == true && veteran == false ..... etc.) {
  query = etc....
if(gender == false && veteran == false ..... etc.) {
  query = etc....
if(gender == null && veteran == false ..... etc.) {
  query = etc....

This is what we call "Dynamic SOQL". Basically, you just build a raw string and pass it to Database.query:

String[] filters = new String[0];
if(gender != null) {
  filters.add('Gender__c = :gender');
if(veteran != null) {
  filters.add('Veteran__c = :veteran');
// etc...

SObject[] results = Database.query(
  'SELECT Id, ... FROM Object WHERE '+
  String.join(filters,' AND ')
| improve this answer | |
  • That was my initial thought as well (mostly typed up), though they are Boolean fields so it's a little hard to understand why it would even need to be dynamic. I guess just so you don't filter against null? – Adrian Larson May 1 '17 at 20:24
  • @AdrianLarson Boolean probably isn't the ideal example, but imagine a picklist that may or may not have a value, etc. – sfdcfox May 1 '17 at 20:44
  • Yeah, like I said, I started typing up almost exactly this answer, then the field type made me pause and think. No point posting the same thing. Maybe it's what they need. – Adrian Larson May 1 '17 at 20:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.