Explain Codes LogoExplain Codes Logo

How do I flip a bit in SQL Server?

sql
bitwise-operations
sql-operations
data-type
Nikita BarsukovbyNikita Barsukov·Feb 12, 2025
TLDR

The XOR operator (^) allows you to flip a bit in SQL Server. With BitColumn = BitColumn ^ 1, you can effortlessly toggle a 0 to 1 or a 1 to 0.

UPDATE YourTable SET BitColumn = BitColumn ^ 1 WHERE YourCondition;

The above operation marks efficient bit inversion in BitColumn for rows meeting YourCondition.

Bitwise operations: A primer

Bitwise operations provide the efficient management of individual bits of a data value with operators such as AND, OR, XOR, and NOT.

Flipping a bit: Your toolkit

Flip 'em all with NOT

The ~ operator can flip all the bits within a value:

-- Watch 'em bits flip! UPDATE your_table SET your_column = ~your_column WHERE your_condition;

Flip via subtraction

Another cool trick to flip a 0 or 1 bit:

-- 1-0=1, 1-1=0; isn't that neat? UPDATE your_table SET your_column = 1 - your_column WHERE your_condition;

Mastering multiple bits flip

When flipping a specific bit among several, utilize bitwise XOR with a bit mask:

-- Time to target that sneaky bit UPDATE your_table SET your_column = your_column ^ bit_mask WHERE your_condition;

Here bit_mask is a binary number, with the bit of interest set to 1 and the rest to 0.

The fine print

While flipping bits, watch out for these considerations:

  • Data type: Ensure bit as data type before operation.
  • Performance: Limit updates using WHERE clause for efficient operation.
  • Precise Flipping: For multiple bits, ensure a perfect bit mask.
  • Safety: Employ TRANSACTION for robust operations on multiple bits / rows.