'DB2 SQL Statement WHERE clause CASE WHEN in multiple conditions

This is what I am trying to do:

SELECT 
    id, name 
FROM 
    users 
WHERE 
    isActive=true
    (AND CASE WHEN {param} != null THEN name={param} ELSE null END)

if the passed {param} is not null then only the AND operator will be added otherwise just isActive=true condition will be used.



Solution 1:[1]

You can use something like COALESCE or (in case of DB2) NVL.

SELECT 
    id, name 
FROM 
    users 
WHERE 
    isActive=true
    AND name=COALESCE({param},name)

You didn't say how you pass parameters/variables, so i'll leave it to you. "{param}" could be replaced with a column or constant in this example

Solution 2:[2]

try this

SELECT 
    id, name 
FROM 
    users 
WHERE 
    isActive=true
 AND (({param} is not null AND name={param}) OR ({param} is null))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 obsaditelnost
Solution 2