MySQL CHAR_LENGTH Function | Length of String

MySQL CHAR_LENGTH is an inbuilt function in MySQL. It returns the length of the input string by counting the number of characters. Also, it ignores whether the characters are single-byte or multi-bytes. It simply counts the number of characters. In this article, we will discuss the MySQL CHAR_LENGTH Function. Also, we will discuss a few examples of using it.

Syntax

CHAR_LENGTH (string)

Parameters

The MySQL CHAR_LENGTH Function expects only one parameter. The string whose length you need to calculate is the input to the function.

Return Value

The function returns the length of the string by counting the characters. Also, it ignores whether characters are a single byte or multibyte. Therefore, the function will return 3 for a string containing three 2-byte characters.

MySQL CHAR_LENGTH Function

Examples

Let’s consider a few examples of using the MySQL CHAR_LENGTH Function.

Example 1: Simple Usage

For instance, consider a simple case of calculating the length of a string.

mysql> SELECT CHAR_LENGTH ("Test String");
+-----------------------------+
| CHAR_LENGTH ("Test String") |
+-----------------------------+
|                          11 |
+-----------------------------+

In the above example, the string contains 11 characters. The function returns the count of characters in the string.

Example 2: Selecting a Table Column

Similarly, you can calculate the length of string from a table using the function.

mysql> SELECT user_name, CHAR_LENGTH(user_name) as length FROM user_description;
+-----------+--------+
| user_name | length |
+-----------+--------+
| chandler  |      8 |
| monica    |      6 |
| ross      |      4 |
+-----------+--------+

Example 3: Using HAVING Query

For example, if you want to select the rows from a table with more than 5 characters in the user_name column. You can achieve this by using the function in a HAVING Query.

mysql> SELECT user_name, CHAR_LENGTH(user_name) as length FROM user_description HAVING length > 5;
+-----------+--------+
| user_name | length |
+-----------+--------+
| chandler  |      8 |
| monica    |      6 |
+-----------+--------+
//Only the rows with more than 5 characters in user_name are selected.

Conclusion

In this article, we discussed the MySQL CHAR_LENGTH Function. You can read more about it on the Official MySQL Documentation. Additionally, you can learn more about MySQL String Functions on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *