Friday, December 20, 2024

MySQL CHAR_LENGTH() Function

 The CHAR_LENGTH() function in MySQL is used to return the number of characters in a string. This function counts the number of characters, not bytes, so it properly handles multibyte characters (like those in UTF-8 or other multibyte encodings).

Syntax:

CHAR_LENGTH(string)

Parameters:

  • string: The string whose length is to be calculated.

Characteristics:

  • Counts characters, not bytes.
  • Returns an integer representing the number of characters.

Example Usage:

1. Basic Example:

SELECT CHAR_LENGTH('Hello') AS Length;
-- Output: 5

2. With Multibyte Characters:

SELECT CHAR_LENGTH('Hello World') AS Length;
-- Output: 4

3. On a Table Column:

Suppose you have a table users with a column username. You can calculate the character length of each username as follows:

SELECT username, CHAR_LENGTH(username) AS Length FROM users;

Comparison with LENGTH():

  • CHAR_LENGTH() counts characters.
  • LENGTH() counts bytes. For example:
SELECT CHAR_LENGTH('Hello'), LENGTH('Hello');
-- Output: CHAR_LENGTH = 2, LENGTH = 6 (in UTF-8 encoding)

Use CHAR_LENGTH() when working with multibyte character sets and focusing on the number of characters, rather than bytes.

No comments:

Post a Comment