MySQL BIT_LENGTH() Function



The MySQL BIT_LENGTH() function is used to find the length of a string in bits. This function accepts a string as input and returns the length of the string in bits. If the input string is NULL, it returns NULL as the result. If the input string is an empty string, this function returns 0 as the result.

The function is useful when working with binary data, as it allows you to determine the number of bits required to store a given string.

Syntax

Following is the syntax of MySQL BIT_LENGTH() function −

BIT_LENGTH(str)

Parameters

This function takes a string or binary value as a parameter.

Return Value

This function returns the length of the given value in string.

Example

Following is an example of the MySQL BIT_LENGTH() function. Here, we are retrieving the length of the string "Tutorialspoint" −

SELECT BIT_LENGTH('Tutorialspoint');

Following is the output of the above code −

BIT_LENGTH('Tutorialspoint')
112

Example

Following is another example with a different string −

SELECT BIT_LENGTH('Test');

Output of the above code is as shown below −

BIT_LENGTH('Test')
32

Example

If you pass a numerical value asan argument, this function returns the number of bits needed to represent that value −

SELECT BIT_LENGTH(2254);

The output obtained is 32, as 2254 requires 32 bits (8 bits per digit) to represent −

BIT_LENGTH(2254)
32

Example

If you pass an empty string as a parameter, the function returns 0 −

SELECT BIT_LENGTH('');

The result produced is as follows −

BIT_LENGTH('')
0

Example

When you pass a NULL value as a parameter, the function returns NULL −

SELECT BIT_LENGTH(NULL);

We get the output as follows −

BIT_LENGTH(NULL)
NULL

Example

You can also pass a column name of a table as a parameter to this function and retrieve the lengths of the values in that column.

Let us create a table named "STUDENTS_TABLE" and insert records into it using CREATE and INSERT statements as shown below −

CREATE TABLE STUDENTS_TABLE (
   name VARCHAR(15),
   marks INT,
   grade CHAR
);

Now, let us insert records into it using the INSERT statement −

INSERT INTO STUDENTS_TABLE VALUES 
('Raju', 80, 'A'),
('Rahman', 60, 'B'),
('Robert', 45, 'C');

The STUDENTS_TABLE obtained is as follows −

name marks grade
Raju 80 A
Rahman 60 B
Robert 45 C

Following query retrieves the length of the name of each student in the STUDENTS_TABLE −

SELECT *, BIT_LENGTH(name) FROM STUDENTS_TABLE;

After executing the above code, we get the following output −

name marks grade BIT_LENGTH(name)
Raju 32 80 A
Rahman 48 60 B
Robert 48 45 C
mysql-bit-length-function.htm
Advertisements