Search code examples
sqlsql-serverperformancecoding-style

Use case statement for skip a filter in where affects the performance of the query?


I make this logic for all query that's requires a optional filter, so my question is this is a bad practice? Is affected the performance of execution?

Example:

SELECT 
    USR_NAME,
    USR_LAST_NAME
FROM 
    KTZ_USER
WHERE
    --- OPTIONAL FILTER ---
    (CASE 
        WHEN @V_USER_NAME IS NULL THEN 1 
        ELSE 
            CASE WHEN USR_NAME = @V_USER_NAME THEN 1 
                 ELSE 0 
            END 
     END) = 1

@V_USER_NAME is the parameter


Solution

  • Nothing wrong with your where clause, but I would use this version:

    SELECT USR_NAME, USR_LAST_NAME
    FROM KTZ_USER
    WHERE @V_USER_NAME IS NULL OR @V_USER_NAME = USR_NAME;
    

    Generally CASE expressions are intended to be used for generating scalar values. We can express your filter logic more directly without using them.