PostgreSQL has a bit_length()
function that returns the number of bits in a given string. We pass the string as an argument and the function returns the number of bits in that string.
Example
Here’s an example to demonstrate:
SELECT bit_length('a');
Result:
8
Here’s another example with various string lengths:
SELECT
bit_length('Cat') AS "Cat",
bit_length('Cafe') AS "Cafe",
bit_length('Café') AS "Café",
bit_length('คาเฟ่') AS "คาเฟ่";
Result:
Cat | Cafe | Café | คาเฟ่
-----+------+------+------
24 | 32 | 40 | 120
bit_length()
vs octet_length()
The bit_length()
function returns the number of bits in the string, whereas octet_length()
returns the number of bytes. Therefore, the result of the bit_length()
function is eight times the length returned by the octet_length()
function (which returns the number of bytes in the string).
Here they are compared:
SELECT
'bit_length()' AS "Function",
bit_length('Cat') AS "Cat",
bit_length('Cafe') AS "Cafe",
bit_length('Café') AS "Café",
bit_length('คาเฟ่') AS "คาเฟ่"
UNION
SELECT
'octet_length()',
octet_length('Cat') AS "Cat",
octet_length('Cafe') AS "Cafe",
octet_length('Café') AS "Café",
octet_length('คาเฟ่') AS "คาเฟ่";
Result:
Function | Cat | Cafe | Café | คาเฟ่
----------------+-----+------+------+------
bit_length() | 24 | 32 | 40 | 120
octet_length() | 3 | 4 | 5 | 15
Passing a Null Argument
Passing a null argument results in null
:
SELECT bit_length(null);
Result:
bit_length
------------
null