MySQL LENGTH() Function

In MySQL, the LENGTH() function returns the length of the specified string in bytes.

The LENGTH() function is the same as OCTET_LENGTH() function.

If you want to return the number of characters, use CHAR_LENGTH() or CHARACTER_LENGTH() function.

LENGTH() Syntax

Here is the syntax of MySQL LENGTH() function:

LENGTH(string)

Parameters

string
Required. A string that needs to be calculated. The parameter can be other data type, such as number or date, and the function will convert it to string first and then calculate the length.

Return value

The LENGTH(string) function returns the length of the specified string in bytes, that is, the number of bytes.

If the parameter is NULL, the function will return NULL.

LENGTH() Examples

Here are some examples of MySQL LENGTH() function.

SELECT
    LENGTH('Hello'),
    LENGTH(''),
    LENGTH(20),
    LENGTH(-20),
    LENGTH(+20),
    LENGTH(NOW()),
    LENGTH(CURDATE()),
    LENGTH('你好'),
    LENGTH(NULL)\G
  LENGTH('Hello'): 5
       LENGTH(''): 0
       LENGTH(20): 2
      LENGTH(-20): 3
      LENGTH(+20): 2
    LENGTH(NOW()): 19
LENGTH(CURDATE()): 10
    LENGTH('你好'): 6
     LENGTH(NULL): NULL

Notice:

  • LENGTH(-20) returns 3. This is because LENGTH(-20) corresponding string is '-20', and LENGTH('-20') returns 3.
  • LENGTH(+20) returns 2. This is because +20 is 20, and LENGTH('20') returns 2.
  • LENGTH(NOW()) is equivalent to LENGTH('2021-04-02 21:18:57').
  • LENGTH('你好') returns 6. This is because one of the Chinese characters occupies 3 bytes in UTF-8 encoding.