PostgreSQL bit_length() Function

The PostgreSQL bit_length() function returns the number of bits in the given string.

If you want to return the number of bytes in a string, use the octet_length() function. Since 1 byte is equal to 8 bits, the return value of bit_length() is 8 times the return value octet_length() for a same string.

If you want to return the number of characters in the string, use char_length(), or character_length() or length().

bit_length() Syntax

This is the syntax of the PostgreSQL bit_length() function:

bit_length(string)

Parameters

string

Required. a string.

Return value

The PostgreSQL bit_length() function returns an integer number that represents the number of bits in the given string.

bit_length() Examples

Simple example

SELECT
    'Bits' AS "String",
    bit_length('a') AS "a",
    bit_length('string') AS "string",
    bit_length('01') AS "01",
    bit_length('你') AS "你";
 String | a | string | 01 | 你
--------+---+--------+----+----
 Bits   | 8 |     48 | 16 | 24

bit_length() vs octet_length()

For the same string, the return of bit_length() is 8 times the return value of octet_length().

SELECT
    bit_length('ab') AS "ab bits",
    octet_length('ab') AS "ab bytes";
 ab bits | ab bytes
---------+----------
      16 |        2