MySQL OCTET_LENGTH() Function

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

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

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

OCTET_LENGTH() Syntax

Here is the syntax of MySQL OCTET_LENGTH() function:

OCTET_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 OCTET_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.

OCTET_LENGTH() Examples

Here are some examples of MySQL OCTET_LENGTH() function.

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

Notice:

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