lef58w
Last Updated: January 28, 2019
·
19.6K
· alexcristea

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.

2 Responses
Add your response

12914

There's a extra ) on your code.

over 1 year ago ·
12915

Thank's for noticing that! :)

over 1 year ago ·