3

Have a database where one table has a field that uses binary bits as flags. So depending on which flags are toggled, you could have a wide range of values so looking at the value alone isn't helpful. ie, a value greater than 8 doesn't mean that the value of 8 is in use (17 for example is 16 + 1).

With this in mind, is there a way to update multiple records to either set or unset a bit (say a value of 8) for a particular field? Some records might have it set while others don't, so don't want to just simple add (or subtract) 8 from it.

2 Answers 2

4

You can use the bitwise OR | and AND & functions;

UPDATE myTable SET myValue = value |  8;   -- set bit 3
UPDATE myTable SET myValue = value & ~8;   -- clear bit 3

(Very) simple SQLfiddle for testing.

Sign up to request clarification or add additional context in comments.

Comments

3

Use the BIT functions. To set bit 1:

update your_table
set bit_field = bit_field | b'0001'

To unset bit 1:

update your_table
set bit_field = bit_field & b'1110'

SQLFiddle demo

4 Comments

So | adds the bit and & only keeps matching bits (set to 1)?
Looking at the link you provided, for unsetting, would ^ be a better alternative? * Marked yours as the answer since you answered first. Thanks.
Nevermind, tried the demo link and see that & is the way to go. Thanks again. :)
@Wolfie & ~ is what you'll want to use for unsetting. ^ will flip the bits every time and not reliably set/unset.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.