MySQL - LENGTH() Function



The MySQL LENGTH() function is used to retrieve the number of characters from the left end of a string.

It calculates the length of the string in bytes, where a multi-byte character is counted as a single character, and returns the length value accordingly.

Syntax

Following is the syntax of MySQL LENGTH() function −

LENGTH(str)

Parameters

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

Return Value

This function returns the number of characters (or bytes for binary data) in the given input.

Example

In the following example, we are determining the length of the string 'tutorialspoint': −

SELECT LENGTH('tutorialspoint');

Following is the output of the above code −

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 LENGTH(225);

The output obtained is as follows −

LENGTH(225)
3

Example

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

SELECT LENGTH('');

We get the output as follows −

LENGTH('')
0

Example

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

SELECT LENGTH(NULL);

The result produced is as shown below −

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, LENGTH(name), marks, LENGTH(marks), grade  
FROM STUDENTS_TABLE;

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

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