Skip to content
Advertisement

Many conditions depends on IF clause within WHERE clause

How can I implement a WHERE clause that depends on one @value condition, like that pseudocode below:

Select * from table
WHERE
IF(@value is not null) 
    Id > 10 and Name = 'example' and Address is not null and ... etc
ELSE 
    Email is not null

Advertisement

Answer

As you’ve seen you can’t use an if like that, but you can create the desired behavior using the and and or logical operators:

SELECT *
FROM   table
WHERE  (@value IS NOT NULL AND 
        id > 10 AND 
        name = 'example' AND 
        address IS NOT NULL AND -- etc...) OR
       (@value IS NULL AND email IS NOT NULL)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement