Search code examples
apexsoql

Conditionally filter on SQL query based on the field value


I want to conditionally filter a SQL query based on the field value of a picklist. How do I do this? If the picklist field value is 'Any Type' then I want to NOT filter the query.

if (picklistValue == 'Any Type') //dont filter     

SELECT Object__c.Name
FROM Object__c
WHERE Object__c.Type__c = :picklistValue

Solution

  • In these scenario's you need to build SOQL dynamically based on your conditions. In your case dynamic SOQL could be something like this:

    List<Object__c > objList = new List<Object__c>();
    String query = 'SELECT Object__c.Name FROM Object__c ';
    
    if(picklistValue == 'Any Type') {// don't filter
        // your code..
    } else {
        // apply filter
        query = query + ' WHERE Object__c.Type__c = \'' + picklistValue + '\';
    
    }
    
    objList = Database.query(query);
    

    You can refer dynamic SOQL documentation for more details.