Pete Freitag Pete Freitag

Toggle a Bit with SQL

databasesweb

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).

shows the transition of states

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
1 1 0
1 0 1
0 1 1
0 0 0

Like this? Follow me ↯

Toggle a Bit with SQL was first published on January 04, 2007.


Comments

Uh... 0 ^ 0 = 0
by Neil Middleton on 01/04/2007 at 9:51:50 AM UTC
Why not: SET active_ind = 1 - active_ind ?
by Rick O on 01/04/2007 at 10:07:28 AM UTC
Oops thanks Neil, I was copying and pasting the rows of hmtl, and forgot to change the last one... Fixed.
by Pete Freitag on 01/04/2007 at 10:26:06 AM UTC
Rick that's a good solution as well, and probably a bit more readable. Thanks!
by Pete Freitag on 01/04/2007 at 10:28:12 AM UTC
Nice tip! I have never used bit-wise manipulation in SQL. It's something I should look into.
by Ben Nadel on 01/05/2007 at 5:35:17 AM UTC
Dale, yes it does work: 1 - 0 = 1 1 - 1 = 0
by Pete Freitag on 01/05/2007 at 7:39:01 AM UTC
if 1 is always 1 then you can use the NOT option to revse the value of active_ind. UPDATE companies SET active_ind = ~active_ind WHERE id = ?
by Kris on 01/05/2007 at 9:22:01 AM UTC
Very elegant. I have been using the ternary operator in PHP, but that requires passing in a variable from the middleware tier. I'll be using this from now on.
by Steve on 01/12/2007 at 11:34:36 AM UTC
Hi, I have a similar problem: I have been banging my head with this one. Problem: I have a SQL Query that sets a bit in a field (I didn't write the query) Code: UPDATE Table_name SET Options=Options|16 WHERE field='value' And Also Code: UPDATE table_name SET Options=Options|8|4|64|128 WHERE field='value' I was told this is setting the bit flags in the field and this query does work correctly. My Question is: How do I reverse the bit settings? I was told to use the ampersand "&" but it didn't work as I had thought. So if I set options|16 I can unset options|16 Thanks in advance -------------------------- so I found the the Tilda "~" (without the quotes) is the reverse binary option, but it didn't do as I thought it would :-(
by Phill Pafford on 11/09/2007 at 12:51:31 PM UTC