I have a similar question to SQL Conditional Where and Conditional WHERE clause in SQL Server, except when the condition is not met, I want to return all rows (as if there were no WHERE clause).
One solution could be to do the following. Note that <ColLetter>
and <ColValue>
are string insertions, where <ColLetter>
will be one of ColA
, ColB
, ColC
, or NULL
, and <ColValue>
will be a value that can appear in one of those columns (or is NULL
if the <ColLetter>
is).
SELECT ID, ColA, ColB, ColC
FROM MainTable t
WHERE (
-- <ColLetter> is not null, corresponding to a column name in MainTable
(ISNULL(<ColLetter>, 0) <> 0 AND t.<ColLetter> = <ColValue>)
OR
-- <ColLetter> is null, I want to return all rows
(ISNULL(<ColLetter>, 0) = 0 AND t.ID is not null)
)
The issue with this is that it checks the ID column for nulls unnecessarily (there won't be any nulls) and it is a large table. Is there a better way to do this?