SQL - Bitwise Operators
In SQL Server, bitwise operators are used to perform operations on individual bits of binary values. SQL Server provides several bitwise operators that allow you to manipulate and compare binary values. The bitwise operators available in SQL Server are:
Bitwise AND ( & ): Performs a bitwise AND operation between two integer values, returning a result that has bits set where both operands have corresponding bits set.
Example:
SELECT 12 & 10 AS Result;
-- Output: 8
Bitwise OR ( | ): Performs a bitwise OR operation between two integer values, returning a result that has bits set where either or both operands have corresponding bits set.
Example:
SELECT 12 | 10 AS Result;
-- Output: 14
Bitwise XOR ( ^ ): Performs a bitwise exclusive OR (XOR) operation between two integer values, returning a result that has bits set where exactly one of the operands has a corresponding bit set.
Example:
SELECT 12 ^ 10 AS Result;
-- Output: 6
Bitwise NOT ( ~ ): Performs a bitwise NOT operation on an integer value, flipping all the bits to their opposite values.
Example:
SELECT ~12 AS Result;
-- Output: -13
Note that the bitwise operators work on integer values. If you use them with non-integer values, SQL Server implicitly converts them to integers before performing the bitwise operation.
These bitwise operators are useful when dealing with binary flags or performing bitwise operations on binary data stored in integer columns.