MySQL If Else condition in Where clause

If Else is slightly similar to OR condition in MySQL. But, here it checks the Statement and go to TRUE Block or FALSE Block.


WHERE IF(Statement, TRUE block, FALSE block)
Here is the user table contains id, name, phone_1, phone_2.
Now I want to get the phone numbers starting with country code 91. In table, phone_1 is primary number and phone_2 is secondary Number.
If phone_1 is missing, it checks phone_2 with the country code 91.
id name phone_1 phone_2
User Table
1 name1 91-1234567890 1234567890
2 name2   91-2345678901
3 name3 91-3456789012 91-3456789012
4 name4 01-4567890123 4567890123
SELECT id ,name
FROM users
WHERE IF('phone_1' != '', 'phone_1', 'phone_2') LIKE  '91%'
Hence we get result as,
id name
1 name1
2 name2
3 name3

MySQL SQL Posted on 2016-04-06 03:12:04