MySQL CHAR_LENGTH() Function



The MySQL CHAR_LENGTH() function is a string function that is used to find the number of characters in a given string or text value.

This function is similar to the LENGTH() function, but it is used specifically for counting the number of characters in a string, whereas LENGTH() counts the number of bytes.

This function accepts a string value as a parameter and returns the length of the given value in characters.

The string functions in SQL are used to manipulate the string values. There are many string functions specified for SQL and CHAR_LENGTH() is one of them.

Syntax

Following is the syntax of MySQL CHAR_LENGTH() function −

CHAR_LENGTH(str)

Parameters

This function takes a string value as a parameter.

Return Value

This function returns the number of characters in the string, measured in Unicode characters.

Example

In this example, we are using the CHAR_LENGTH() to find the number of characters in the string 'tutorialspoint' −

SELECT CHAR_LENGTH('tutorialspoint');

Following is the output of the above code −

CHAR_LENGTH('tutorialspoint')
14

Example

Here is another example where we are determining the character count in the string 'test' −

SELECT CHAR_LENGTH('test');

Output of the above code is as shown below −

CHAR_LENGTH('test')
4

Example

If you pass a numerical value as a parameter, the CHAR_LENGTH() function counts the number of digits in the value and returns it as a result −

SELECT CHAR_LENGTH(225);

The output obtained is as shown below −

CHAR_LENGTH(225)
3

Example

When you pass an empty string as a parameter, the function returns a length of 0 −

SELECT CHAR_LENGTH('');

The result produced is as follows −

CHAR_LENGTH('')
0

Example

If you pass a NULL value as a parameter, the CHAR_LENGTH() function returns NULL −

SELECT CHAR_LENGTH(NULL);

We get the output as follows −

CHAR_LENGTH(NULL)
NULL

Example

You can also use the CHAR_LENGTH() function with column names in a table to retrieve the lengths of values in a specific 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 names and marks columns of the students from the STUDENTS_TABLE −

SELECT name, CHAR_LENGTH(name), marks, CHAR_LENGTH(marks) 
FROM STUDENTS_TABLE;

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

name CHAR_LENGTH(name) marks CHAR_LENGTH(marks)
Raju 4 80 2
Rahman 6 60 2
Robert 6 45 2
mysql-char-length-function.htm
Advertisements