This page in other versions: 8.4 / 9.0 / 9.1 / 9.2 / 9.3  |  Development versions: devel  |  Unsupported versions: 7.1 / 7.2 / 7.3 / 7.4 / 8.0 / 8.1 / 8.2 / 8.3

8.10. Bit String Types

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(n) and bit varying(n), where n is a positive integer.

bit type data must match the length n 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 length n; longer strings will be rejected. Writing bit without a length is equivalent to bit(1), while bit varying without a length specification means unlimited length.

Note: If one explicitly casts a bit-string value to bit(n), it will be truncated or zero-padded on the right to be exactly n bits, without raising an error. Similarly, if one explicitly casts a bit-string value to bit varying(n), it will be truncated on the right if it is more than n bits.

Refer to Section 4.1.2.5 for information about the syntax of bit string constants. Bit-logical operators and string manipulation functions are available; see Section 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 in Section 8.3 for character strings).

Comments


July 29, 2011, 11:21 p.m.

If you would like to send some Bit String from c using libpq and want to use binary format than try this simple example:

CREATE TABLE bitTable (
id int,
bitString BIT(32)
);
INSERT INTO bitTable VALUES(1,B'11000001000000010000000100000011');
---------------------------------------------------

//First byte is the lenght and the second is what we want to set
char bits[8] = { 0, 0, 0, 32, 255,255,255,255 };
const char *params[1] = ;
int paramsLen[1] = ;
int paramsFormat[1] = 1;

yourResultPointer = PQexecParams(yourPGconnPointer,"Update bitTable SET bitString=$1::bit(32) WHERE id=1;",1,NULL,params,paramsLen,paramsFormat,1);

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group