MySQL OCTET_LENGTH() Function



The MySQL OCTET_LENGTH() function returns the length of the provided string, measured in bytes.

If you pass a multibyte character as a parameter, this function counts it as a single character and returns the length value accordingly. If you pass NULL to this function, it returns NULL as result.

The MySQL OCTET_LENGTH() is a synonym for the function LENGTH().

Syntax

Following is the syntax of MySQL OCTET_LENGTH() function −

OCTET_LENGTH(str)

Parameters

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

Return Value

This function returns the number of bytes in the provided input.

Example

In the following example, we are using the OCTET_LENGTH() function to determine the length in bytes of the string 'tutorialspoint' −

SELECT OCTET_LENGTH('tutorialspoint');

Following is the output of the above code −

OCTET_LENGTH('tutorialspoint')
14

Example

When you pass a numerical value as a parameter, this function counts the number of digits in the given value and returns that count −

SELECT OCTET_LENGTH(225);

The output obtained is as follows −

OCTET_LENGTH(225)
3

Example

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

SELECT OCTET_LENGTH('');

We get the output as follows −

OCTET_LENGTH('')
0

Example

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

SELECT OCTET_LENGTH(NULL);

The result produced is as shown below −

OCTET_LENGTH(NULL)
NULL

Example

You can also pass a column name of a table as a parameter to this function and get the length of the values in a particular 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 lengths of student names from the 'STUDENTS_TABLE' −

SELECT name, OCTET_LENGTH(name), marks, OCTET_LENGTH(marks), grade  
FROM STUDENTS_TABLE;

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

name OCTET_LENGTH(name) marks OCTET_LENGTH(marks) grade
Raju 4 80 2 A
Rahman 6 60 2 B
Robert 6 45 2 C
mysql-octet-length-function.htm
Advertisements