SQL Bitwise Operator-interview
Q1. What are bitwise operators in SQL?
Bitwise operators in SQL are used to perform operations on binary representations of integers.
Common bitwise operators include:
- & (Bitwise AND)
- | (Bitwise OR)
- ^ (Bitwise XOR)
- ~ (Bitwise NOT)
- << (Left Shift)
- >> (Right Shift)
Q2. How does the Bitwise AND (&) operator work in SQL?
The Bitwise AND operator compares each bit of two integers and returns 1 only if both bits are 1.
Example:
SELECT 5 & 3 AS Result;
Binary of 5 → 101
Binary of 3 → 011
Result → 001 (which equals 1)
Q3. What is the difference between Bitwise OR (|) and XOR (^) operators?
- Bitwise OR (|) returns 1 if either bit is 1.
- Bitwise XOR (^) returns 1 only if exactly one bit is 1.
SELECT 5 | 3 AS OR_Result, 5 ^ 3 AS XOR_Result;
Q4. What does the Bitwise NOT (~) operator do?
The Bitwise NOT (~) operator inverts each bit in a number — turning 1 into 0 and 0 into 1.
Binary of 5 → 00000101
Result → 11111010 (which represents -6 in signed integer form)
SELECT 5 | 3 AS OR_Result, 5 ^ 3 AS XOR_Result;
SELECT ~5 AS Result;
Q5. What are practical use cases of bitwise operators in SQL?
Bitwise operators are used in:
- Flag-based filtering (e.g., checking multiple status flags in a single column)
- Permission systems (e.g., user roles represented as bit masks)
- Performance optimization for compact storage and fast filtering