(Very easy trick - this post is that long only because Im trying to fully explain whats going on. Hope you like it.)
Summary
By passing in optional values you can have the query ignore specific WHERE clauses. This effectively makes that particular clause become a 1=1 statement. Awesome when u're not sure what optional values will be provided.
Details
Instead of writing a lot of similar queries just for different filter combinations writing just one and exploit bool logic.
I use it a lot in conjuction with typed datasets in .net. For example, let say we have a query like that:
select id, name, age, rank, hometown from .........;
We've created fill/get method that loads all data.
Now, when we need to filter for id - we're adding another fill/get method:
select id, name, age, rank, hometown from ..... where id=@id;
Then we need to filter by name and hometown - next method:
select id, name, age, rank, hometown from .... where name=@name and hometown=@hometown;
Suppose now we need to filter for all other columns and their combinations - we quickly end up creating a mess of similar methods, like method for filtering for name and hometown, rank and age, rank and age and name etc. etc.
One option is to create suitable query programatically, the other, much simpler, is to use one fill/get method that will provide all filtering possibilites:
select id, name, age, rank, hometown from .....
where
(@id = -1 OR id = @id) AND
(@name = '*' OR name = @name OR (@name is null AND name is null)) AND
(@age = -1 OR age = @age OR (@age is null AND age is null)) AND
(@rank = '*' OR rank = @rank OR (@rank is null AND rank is null) AND
(@hometown = '*' OR hometown = @hometown OR (@hometown is null AND hometown is null);
Now we have all possible filterings in one query. Let's say get method name is get_by_filters with signature:
get_by_filters(int id, string name, int? age, string rank, string hometown)
Want to filter just by name? :
get_by_filters(-1,"John",-1,"*","*");
By age and rank where hometown is null? :
get_by_filters(-1, "*", 23, "some rank", null);
etc. etc.
Just one method, one query and all filter combinations. It saved me a lot of time.
One drawback is that you have to "reserve" integer/string for "doesn't matter" filter. But you shouldn't expect an id of value -1 and person with name '*' (of course this is context dependant) so not big problem imho.
edit:
Just to quickly explain the mechanism, lets take a look at first line after where:
(@id = -1 OR id = @id) AND ...
when parameter @id is set to -1 the query becomes:
(-1 = -1 OR id = -1) AND ...
thanks to short circuit logic the second part of OR is not going to be even tested: -1 = -1 is always true.
If parameter @id was set to, lets say, 77:
(77 = -1 OR id = 77) AND ...
then 77 = -1 is obviously false, so test for column id equal 77 will be performed. Same for other parameters. This is really easy yet powerful.