Pages

About Me

My photo
ForEach(Minute in MyLife) MyExperience ++;

Wednesday, May 4, 2011

SQL query to toggle between 0 and 1

UPDATE products SET
in_stock = CASE WHEN in_stock = 1 THEN 0 ELSE 1 END;
Or sometimes the developer tries to accomplish the same thing with an overly complex subquery. We can greatly simplify what we’re trying to do with just this query:

UPDATE products SET in_stock = in_stock ^ 1;

The trick is using the caret (“^”), which is the bitwise XOR operator (MySQL, MS SQL Server) with either a “0? or a “1?. For those of you who’s binary math is a bit rusty, remember:

1 ^ 1 = 0
0 ^ 0 = 0
1 ^ 0 = 1
0 ^ 1 = 1

No comments:

Post a Comment