BIT

The BIT and VARBIT data types stores bit arrays.With BIT, the length is fixed; with VARBIT, the length can be variable.

Aliases

The name BIT VARYING is an alias for VARBIT.

Syntax

Bit array constants are expressed as literals. For example, B'100101' denotes an array of 6 bits.

For more information about bit array constants, see the constants documentation on bit array literals.

For usage, see the Example below.

Size

The number of bits in a BIT value is determined as follows:

Type declarationLogical size
BIT1 bit
BIT(N)N bits
VARBITvariable with no maximum
VARBIT(N)variable with a maximum of N bits

The effective size of a BIT value is larger than its logical numberof bits by a bounded constant factor. Internally, CockroachDB storesbit arrays in increments of 64 bits plus an extra integer value toencode the length.

The total size of a BIT value can be arbitrarily large, but it isrecommended to keep values under 1 MB to ensure performance. Abovethat threshold, writeamplification andother considerations may cause significant performance degradation.

Example

  1. > CREATE TABLE b (x BIT, y BIT(3), z VARBIT, w VARBIT(3));
  1. > SHOW COLUMNS FROM b;
  1. column_name | data_type | is_nullable | column_default | generation_expression | indices | is_hidden
  2. +-------------+-----------+-------------+----------------+-----------------------+-----------+-----------+
  3. x | BIT | true | NULL | | {} | false
  4. y | BIT(3) | true | NULL | | {} | false
  5. z | VARBIT | true | NULL | | {} | false
  6. w | VARBIT(3) | true | NULL | | {} | false
  7. rowid | INT | false | unique_rowid() | | {primary} | true
  1. > INSERT INTO b(x, y, z, w) VALUES (B'1', B'101', B'1', B'1');
  1. > SELECT * FROM b;
  1. x | y | z | w
  2. +---+-----+---+---+
  3. 1 | 101 | 1 | 1

For type BIT, the value must match exactly the specified size:

  1. > INSERT INTO b(x) VALUES (B'101');
  1. pq: bit string length 3 does not match type BIT
  1. > INSERT INTO b(y) VALUES (B'10');
  1. pq: bit string length 2 does not match type BIT(3)

For type VARBIT, the value must not be larger than the specified maximum size:

  1. > INSERT INTO b(w) VALUES (B'1010');
  1. pq: bit string length 4 too large for type VARBIT(3)

Supported casting and conversion

BIT values can be cast to any of the following data types:

TypeDetails
INTConverts the bit array to the corresponding numeric value, interpreting the bits as if the value was encoded using two's complement. If the bit array is larger than the integer type, excess bits on the left are ignored. For example, B'1010'::INT equals 10.
STRINGPrints out the binary digits as a string. This recovers the literal representation. For example, B'1010'::INT equals '1010'.

See also

Data Types

Was this page helpful?
YesNo