Toggle a Bit with SQL
I am working on a management dashboard for a client, which uses some AJAX here and there. One simple but really nice feature is that you can enabled or disable things just by clicking on an icon, the state is updated in the background using AJAX (I also add some animation to let the user know that it has been updated).
I wanted to be able to toggle the state of the
bit field without a care of the current state. Here's how you can do that in SQL:
UPDATE companies SET active_ind = active_ind ^ 1 WHERE id = ?
I'm using a
^ Bitwise (Exclusive OR or XOR) operator here to do this. To understand what's going on here let's look at a truth table for XOR:
|p||q||p ^ q|