I've this query:
SELECT `id` , `naam` FROM `klanten` WHERE ( `email` LIKE '%@domain.nl%' OR `email2` LIKE '%@domain.nl%' )
But I want to do something like this:
SELECT `id` , `naam` FROM `klanten` WHERE IF(`email` > 0, `email` LIKE '%@domain.nl%' , `email2` LIKE '%@domain.nl%' )
How to check if email exist? I want to use email and if this field is empty I want to use email2. How do I accomplish this?
IF… ELSE clause is very handy and whenever you need to perform any conditional operation, you can achieve your results using it. But there are some limitations in IF… ELSE, and one of the limitations is that you cannot use it in WHERE clause.
The SQL IN OperatorThe IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.
IF
is used to select the field, then the LIKE
clause is placed after it:
SELECT `id` , `naam` FROM `klanten` WHERE IF(`email` != '', `email`, `email2`) LIKE '%@domain.nl%'
You want to use coalesce()
:
where coalesce(email, email2) like '%[email protected]%'
If you want to handle empty strings ('') versus NULL, a case works:
where (case when email is NULL or email = '' then email2 else email end) like '%[email protected]%'
And, if you are worried about the string really being just spaces:
where (case when email is NULL or ltrim(email) = '' then email2 else email end) like '%[email protected]%'
As an aside, the sample if
statement is really saying "If email starts with a number larger than 0". This is because the comparison is to 0, a number. MySQL implicitly tries to convert the string to a number. So, '[email protected]' would fail, because the string would convert as 0. As would '[email protected]'. But, '[email protected]' and '[email protected]' would succeed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With