Friday, December 20, 2024

MySQL LENGTH() Function

 The LENGTH() function in MySQL is used to return the length of a string in bytes. It counts the number of bytes, which can differ from the number of characters if the string contains multi-byte characters (e.g., characters from Unicode character sets like UTF-8).

Syntax:

LENGTH(string)
  • string: The string whose length (in bytes) you want to determine.

Example:

SELECT LENGTH('Hello World');

This would return 11, because "Hello World" has 11 characters, and since it's using single-byte characters in the default character set, it counts them as 11 bytes.

If you are using a multi-byte character set (e.g., UTF-8), the result can be different. For example:

SELECT LENGTH('Hello');

This could return 6 because each character in "Hello" might occupy 3 bytes in UTF-8 encoding.

Difference Between LENGTH() and CHAR_LENGTH():

  • LENGTH(): Returns the length in bytes.
  • CHAR_LENGTH() or CHARACTER_LENGTH(): Returns the length in characters (not bytes).

Example:

SELECT LENGTH('Hello'), CHAR_LENGTH('Hello');

This would return:

  • LENGTH('Hello'): 6 (3 bytes per character in UTF-8).
  • CHAR_LENGTH('Hello'): 2 (2 characters).

No comments:

Post a Comment