Postgresql 中文操作指南

8.10. Bit String Types #

位串是 1 和 0 的串。它们可用于存储或可视化位掩码。有两种 SQL 位类型:bit(_n)_ 和 bit varying(_n), where _n 是正整数。

bit 类型数据必须与长度 n 完全匹配;存储更短或更长的位串时出错。bit varying 数据最多可变长到最大长度 n;将拒绝较长的字符串。不带长度编写 bit 等同于 bit(1),而_bit varying_ 不带长度说明意味着长度无限制。

Note

如果明确将位串值强制转换为 bit(_n), it will be truncated or zero-padded on the right to be exactly _n 位,而不会引发错误。类似地,如果明确将位串值强制转换为 bit varying(_n), it will be truncated on the right if it is more than _n 位。

有关位字符串常量的语法信息,请参阅 Section 4.1.2.5。提供了位逻辑运算符和字符串操作函数;请参阅 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

位字符串值每个8位组需要1个字节,另外根据字符串的长度需要5个或8个字节的开销(但长值可以压缩或移出,如 Section 8.3中关于字符字符串的解释)。