Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If else on WHERE clause

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?

like image 493
botenvouwer Avatar asked Mar 01 '13 16:03

botenvouwer


People also ask

Can we use if else in WHERE clause?

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.

Can we use in operator with 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.


2 Answers

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%' 
like image 149
Rocket Hazmat Avatar answered Sep 20 '22 16:09

Rocket Hazmat


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.

like image 37
Gordon Linoff Avatar answered Sep 21 '22 16:09

Gordon Linoff