SQL: Toggle 1 and 0 Value in an Update SQL Statement

I tend to use a lot of tinyint columns as controllers for my database-held objects, usually sticking to the convention of 1 means on and 0 means off. In other words, the perfect target for a SQL toggle statement!

In order to toggle update a value in SQL, we’ll need to make use of the common SQL control flow function IF. The IF function takes three parameters, the first being the test expression, the second being the term to return if the test expression passes and the third being the term returned if the test expression fails.

So putting this into our 1 or 0 toggle SQL statement, we get:

UPDATE `table` SET `column` = IF(`column` = 1, 0, 1) WHERE `id` = x

It’s pretty intuitive to see what is going on above, now that we understand the form of the fabulous IF SQL function!

Nifty.

Related Link: http://dev.mysql.com/doc/refman/5.1/en/control-flow-functions.html#function_if

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in MySQL, Tutorials and tagged 1 or 0, , , . Bookmark the permalink.
    blog comments powered by Disqus