Site icon TestingDocs.com

MySQL CHAR_LENGTH Function

Overview

In this tutorial, we will learn about the MySQL CHAR_LENGTH Function. This function returns the
length of the string i.e the umber of characters in the string.

Syntax

The general the syntax for a function call includes the function name followed by parenthesis
(which contains the String argument):

CHAR_LENGTH(string_argument)

This function can be invoked with a string argument or column names. The function returns the number that is used in place of the function call when the expression is evaluated.

Examples

In the first example, we will call the function with a sample string argument. Let’s count the number of characters in the string ‘abcd’.

mysql> SELECT CHAR_LENGTH(‘abcd’);
+———————+
| CHAR_LENGTH(‘abcd’) |
+———————+
| 4 |
+———————+

In the next example, we will calculate the number of characters in a table column. We will consider the
Country database table from the world MYSQL database. The Name column is a String datatype column CHAR/VARCHAR.

mysql> SELECT Name, CHAR_LENGTH(Name)
             -> FROM Country
             -> WHERE Continent = ‘North America’;

 

There is a notable difference between CHAR_LENGTH and LENGTH functions.  CHAR_LENGTH() counts multi-byte character as a single character. For example, for a string containing seven 2-byte characters, LENGTH() returns 14, whereas CHAR_LENGTH() function returns 7.

MySQL Tutorials

MySQL Tutorials on this website:

https://www.testingdocs.com/mysql-tutorials-for-beginners/

For more information on MySQL Database:

https://www.mysql.com/

Exit mobile version