How do you perform a bitwise operation in SQL?
Posted by BobHarris
Last Updated: June 19, 2024
In SQL, bitwise operations can be performed using specific operators that are available in most SQL database management systems. The most commonly used bitwise operators are: 1. Bitwise AND (&): This operator compares each bit of two integers and returns a new integer with bits set to 1 where both input bits are 1. 2. Bitwise OR (|): This operator compares each bit of two integers and returns a new integer with bits set to 1 where at least one of the input bits is 1. 3. Bitwise XOR (^): This operator compares each bit of two integers and returns a new integer with bits set to 1 where the corresponding bits of the operands are different. 4. Bitwise NOT (~): This operator inverts all bits of the integer. Here's how to use these operators in SQL. Note that availability and specific syntax can vary slightly between SQL dialects, so double-check the documentation for your specific SQL database (like MySQL, PostgreSQL, SQL Server, Oracle, etc.).
Examples
1. Bitwise AND:
SELECT 5 & 3 AS BitwiseAnd;  -- 5 is 0101 in binary, 3 is 0011; Result is 1 (0001)
2. Bitwise OR:
SELECT 5 | 3 AS BitwiseOr;   -- Result is 7 (0111)
3. Bitwise XOR:
SELECT 5 ^ 3 AS BitwiseXor;  -- Result is 6 (0110)
4. Bitwise NOT:
SELECT ~5 AS BitwiseNot;     -- Result is -6 (inverts the bits of 5: 0101 becomes 1010)
Bitwise Operations on Table Columns
You can also use bitwise operations on columns in a table:
SELECT id, status, status & 1 AS IsActive
FROM users
WHERE (status & 2) > 0;  -- This selects users whose status has the second bit set
Important Notes
- The specific behavior and support for bitwise operations can vary between SQL databases. For example, BITAND or BIT_XOR functions may exist in some SQL databases rather than using a simple operator. - Make sure to verify the syntax and capabilities in your SQL dialect when implementing bitwise operations.