MySQL: Using IF in a WHERE clause
The MySql IF
statement works like this:
IF(<condition>, <value if true>, <value if false>)
In the following example, the first query would return 1
and the second 0
:
SELECT IF( 'a' = 'a', 1, 0 );
SELECT IF( 'a' = 'b', 1, 0 );
The example below shows how to use the IF
statement in a WHERE
query:
SELECT `my_field`
FROM `my_table`
WHERE IF(`my_field` = 'somevalue', 1, 0) = 1
Read more about this here.
Written by Alex Cristea
Related protips
2 Responses
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/84152/0_NFyu8TxKcY7l9htqq8V08GOlvgyPN_tq96e18GxTEZe_wF5N43u8aCI7U1puckP4vXYt753O6cjr.jpeg)
There's a extra )
on your code.
over 1 year ago
·
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/46059/IMG_0001.jpg)
Thank's for noticing that! :)
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Mysql
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#