• Hi Thomas,

    "the example given in the question" - Huh? I just went back and checked the question to make sure, but there is no example at all given in the question.

    "Can anyone give an example of where a CASE expression should/could be used in a WHERE clause?" - Lots, if I have to. A very common one is that of a stored procedure with an optional search argument:

    SELECT Something

    FROM SomeTable

    WHERE SomeColumn = CASE WHEN @SomeParameter = 'ALL' THEN SomeColumn ELSE @SomeParameter END;

    Or a stored procedure for searching places in a radius that can be specified in either miles or kilometers:

    SELECT Something

    FROM SomeTable

    WHERE DistanceInKM < CASE WHEN @unit = 'miles' THEN 1.609344 ELSE 1 END * @MaxDistance;

    Or a table that uses the column FoundingDate for business customers and BirthDate for people customers in a query that reports customers older than 50 years:

    SELECT Something

    FROM SomeTable

    WHERE CASE WHEN CustType = 'B' THEN FoundingDate ELSE BirthDate END < '19570424';

    Need I go on?


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/