- Salesforce Development Posts by Matt Lacey

Keeping It Clean: Easy Conditional Where Clause

Posted 2011-12-16

First things first, a disclaimer: this is clearly not the most efficient way of doing this in terms of the query execution, however, it is a nice way to keep your code neat and compact whilst negating the need for dynamic SOQL. Dynamic SOQL is a fantastic tool, but it's always a tad ugly and I always seem to forget to query a field, which of course, the compiler can't warn you about.

So say you want to add a conditional to your where clause, but in some circumstances you won't want to use it—for instance if you specify null then you don't care whether a field matches your condition, you want the records regardless. A nice easy way to do this, is to simply use a ternary and making use of SOQL's LIKE keyword. Of course, we're talking about text fields and string filters.

Instead of having two queries in your code (one with the filter, one without) and instead of having to build dynamic SOQL, you can just do something like this:

... AND SomeField like : (strSomeFilter == '' ? '%' : strSomeFilter)

Simple, clean, and (in this programmer's opinion at least) effective. Some people have their own preferences in these scenarios, and I'm always of the opinion that there are many valid solutions to a problem. Leave a comment if you do have a strong opinion on this method, or if you have a technique for doing something similar, let's share the brain wealth!