I’ve been looking to find a good way to do a SQL query where I can have a where statement which, if left blank, will act like it wasn’t there at all. I’ve found this, which seems to work quite well:
WHERE (Column = @value OR @value is null)
If I specify a value for @value, the search is filtered like I want. But if I pass in null, it’s like saying @value can be anything. I like this. This is good. What I don’t understand though is, why does this work like this?
If @value is null, your WHERE clause:
reduces to
(This is similar to
if (Column == value || true)in other common languages)An OR conjunction is true if either of its operands (sides) are true: SQL uses three valued logic
And so:
Column = @value.