I use a lot of tinyint columns for my PHP projects, usually sticking to the convention of 1 means on/true and 0 means off/false. In other words, the perfect target for a SQL toggle statement! I recently found out a nifty trick to toggle a column between 1 and 0.
To toggle a value, we can make use of the common SQL control flow function IF. The IF function takes three parameters, first the test expression, the second the term to return if the test expression is true and the third being term to return if the test expression fails.
For example:
UPDATE `table` SET `column` = IF(`column` = 1, 0, 1) WHERE `id` = x
It’s pretty intuitive to understand what is going on above, now that we understand the structure of the wonderful IF function in SQL! ![]()
See Also: MySQL 5.1 Reference Manual: Control Flow Functions#IF function
October 25, 2011