MySQL MID() Function

In MySQL, the MID() function returns a substring of a specified length starting from the specified position.

MID() Syntax

Here is the syntax of MySQL MID() function:

MID(str, pos, len)

MID(str, pos, len) is the same as SUBSTRING(str, pos, len) and SUBSTR(str, pos, len) functions.

Parameters

str
Required. The original string from which to extract the substring.
pos
Required. The start position of substring. It can be positive or negative. If it is negative, extract the substring from the end of the string.
len
Optional. The length (number of characters) of the substring. If not specified, extract a substring to the end of the original string.

Return value

The MID() function returns a substring of a specified length starting from the specified position.

  • If pos is equals or exceeds the length of the original string, the function will return an empty string ''.
  • If any parameter is NULL, the function will return NULL.

MID() Examples

SELECT
    MID('Hello', 1, 2),
    MID('Hello', 2, 2),
    MID('Hello', 1),
    MID('Hello', 1, 8),
    MID('Hello', -1, 2),
    MID('Hello', 8, 2),
    MID('Hello', 0, 2),
    MID('Hello', 0),
    MID(NULL, 1, 1)\G
 MID('Hello', 1, 2): He
 MID('Hello', 2, 2): el
    MID('Hello', 1): Hello
 MID('Hello', 1, 8): Hello
MID('Hello', -1, 2): o
 MID('Hello', 8, 2):
 MID('Hello', 0, 2):
    MID('Hello', 0):
    MID(NULL, 1, 1): NULL