Bit strings are strings of 1's and 0's. They can be used to store or visualize bit masks. There are two SQL bit types:bit(
andn
)bit varying(
, wheren
)n
is a positive integer.
bit
type data must match the lengthn
exactly; it is an error to attempt to store shorter or longer bit strings.bit varying
data is of variable length up to the maximum lengthn
; longer strings will be rejected. Writingbit
without a length is equivalent tobit(1)
, whilebit varying
without a length specification means unlimited length.
If one explicitly casts a bit-string value tobit(
, it will be truncated or zero-padded on the right to be exactlyn
)n
bits, without raising an error. Similarly, if one explicitly casts a bit-string value tobit varying(
, it will be truncated on the right if it is more thann
)n
bits.
Refer toSection 4.1.2.5 for information about the syntax of bit string constants. Bit-logical operators and string manipulation functions are available; seeSection 9.6.
Example 8.3. Using the Bit String Types
CREATE TABLE test (a BIT(3), b BIT VARYING(5));INSERT INTO test VALUES (B'101', B'00');INSERT INTO test VALUES (B'10', B'101');ERROR: bit string length 2 does not match type bit(3)
INSERT INTO test VALUES (B'10'::bit(3), B'101');SELECT * FROM test;a | b-----+----- 101 | 00 100 | 101
A bit string value requires 1 byte for each group of 8 bits, plus 5 or 8 bytes overhead depending on the length of the string (but long values may be compressed or moved out-of-line, as explained inSection 8.3 for character strings).
If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please usethis form to report a documentation issue.