Bit strings are sequences of 1s and 0s used to store or visualize bit masks. PolarDB for Oracle supports two SQL bit types: bit(n) and bit varying(n), where n is a positive integer.
Type overview
| Declaration | Behavior |
|---|---|
BIT | Fixed length: 1 bit (equivalent to BIT(1)) |
BIT(n) | Fixed length: exactly n bits |
BIT VARYING | Variable length: no maximum |
BIT VARYING(n) | Variable length: up to n bits |
Length constraints
BIT(n) requires values to match the declared length exactly. Inserting a shorter or longer bit string raises an error.
BIT VARYING(n) accepts any bit string up to n bits. Strings longer than n are rejected.
Explicit casting changes this behavior. Casting a value to BIT(n) truncates or zero-pads the value on the right to exactly n bits — no error is raised. Casting to BIT VARYING(n) truncates values longer than n bits on the right.
Examples
The following examples walk through common operations: creating a table, inserting valid values, handling a length mismatch error, and using an explicit cast to fix it.
Create a table with both bit types:
CREATE TABLE test (a BIT(3), b BIT VARYING(5));Insert valid values:
INSERT INTO test VALUES (B'101', B'00');Both values are within the declared lengths and insert successfully.
Insert a value that violates the fixed-length constraint:
INSERT INTO test VALUES (B'10', B'101');ERROR: bit string length 2 does not match type bit(3)B'10' is 2 bits, but column a requires exactly 3. The insert fails.
Use an explicit cast to fix the mismatch:
INSERT INTO test VALUES (B'10'::bit(3), B'101');The cast right-pads B'10' with a zero to produce 100, satisfying the BIT(3) constraint.
Query the table:
SELECT * FROM test; a | b
-----+-----
101 | 00
100 | 101Storage
A bit string requires 1 byte per 8 bits, plus 5 or 8 bytes of overhead depending on the string length.
What's next
For bit string literal syntax, see Constants.
For bit-logical operators and string manipulation functions, see Bit string functions and operators.