Convert an integer to its binary (base-2) string representation.
TO_BIN(n)
## Overview Returns the binary (base-2) string representation of the given integer. TO_BIN is the inspection primitive for bitmask columns, feature flags, and any integer-valued field whose individual bits carry meaning. The output has no '0b' prefix and no leading zeros (except for the input 0, which returns '0'). TO_BIN is complementary to TO_OCT (base 8) and TO_HEX-style functions (base 16) where available. Use it whenever you need to see the exact bit pattern of a value. ## Behavior - Accepts INTEGER or BIGINT input. - Returns a STRING without leading zeros and without a base prefix. - Returns NULL if the argument is NULL. - TO_BIN(0) returns the string '0'. - Negative values are represented in two's complement at the full width of the input type (32 bits for INTEGER, 64 bits for BIGINT). ## Numeric precision - TO_BIN is exact: every bit of the input is preserved in the output. - The length of the output is variable (log2(|n|) + 1 for positive n, full width for negative n). ## Compatibility - Matches the PostgreSQL TO_BIN function. - Complementary to TO_OCT and to engine-specific TO_HEX or HEX functions.
| Name | Type | Description |
|---|---|---|
n | Specifies the integer value to convert. Accepts INTEGER or BIGINT types. Negative values are represented using two's complement notation with the full width of the input type. |
-- Binary of 10
SELECT TO_BIN(10); -- '1010'
-- Binary of 0
SELECT TO_BIN(0); -- '0'
-- Binary of 255 (all bits set in a byte)
SELECT TO_BIN(255); -- '11111111'
-- Binary of 1
SELECT TO_BIN(1); -- '1'
-- Binary of a large value
SELECT TO_BIN(1024); -- '10000000000'
-- NULL propagation
SELECT TO_BIN(NULL); -- NULL