MySQL: Using IF in a WHERE clause
Posted January 6th, 2010 in MySql
I recently needed to use an IF statment in a WHERE clause with MySQL. This isn't the most ideal situation and should probably be avoided normally but we needed to do it for one reason or another and this post shows how to do it.
How IF works
If works like this:
IF(<condition>, <value if true>, <value if false>)
So as an example, the first query below would return 1 and the second 0:
SELECT IF( 'a' = 'a', 1, 0 ); SELECT IF( 'a' = 'b', 1, 0 );
Using IF in a WHERE query
The following example shows how to use IF in a WHERE query.
SELECT ... WHERE ... AND IF(myfield = 'somevalue', 1, 0) = 1
In the above example, if the value from the column "myfield" matches "somevalue" then the IF function will evaluate to 1. This is then compared with the value 1 which returns true or false for this part of the where condition depending whether the IF function returns 1 or 0.
This simple example would be obviously be better represented like this and would be more efficient because it's not using an IF function:
SELECT ... WHERE ... AND myfield = 'somevalue'
Our actual code had a nested IF which simplified the original query and looked something like this:
SELECT ... WHERE ... AND IF(myfield = 'somevalue', IF(otherfield = 12345, 1, 0), 0) = 1
An alternative to the above without using IF functions would look something like this:
SELECT ... WHERE ... AND ( (myfield = 'somevalue' AND otherfield = 12345) OR myfield != 'somevalue' )
But should you use IF in a WHERE clause?
Probably not. It's probably not the most efficient way of doing things. Ideally you should have already filtered with other WHERE statements otherwise it will have to do the IF function on every row in the database.
I've posted this mainly as a reference to show how it can be done. I'll leave whether or not it should be done up to you :)
Related posts:
- MySQL: Using BETWEEN in a SQL query (Friday, November 6th 2009)
- Selecting substrings with MySQL using LOCATE and SUBSTRING (Wednesday, June 3rd 2009)
- MySQL: Delete records in one table that are not in another (Wednesday, May 13th 2009)
- MySQL: Find records in one table that are not in another - revised (Friday, May 8th 2009)
- String concatenation with MySQL - Part 1 (Wednesday, March 4th 2009)
- Insert multiple records into MySQL with a single query (Wednesday, December 3rd 2008)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

