MySQL MID() Function
The MID()
function in MySQL extracts a portion (substring) from a string, starting at a specified position and extending for a given length. It's a fundamental tool for manipulating text data.
MID(): Definition and Usage
MID()
is very useful for pulling out specific parts of strings. You provide the string, the starting position, and the desired length. The starting position is 1-based (the first character is position 1), and you can use negative numbers to count from the end of the string (-1 for the last character).
Equivalent Functions
The MID()
function is equivalent to both SUBSTR()
and SUBSTRING()
in MySQL.
Syntax
Syntax
MID(string, start, length)
Parameter Values
Parameter | Description |
---|---|
string |
The string to extract from. This is required. |
start |
The starting position (1-based index, positive or negative). This is required. |
length (Optional) |
The number of characters to extract. If omitted, the function extracts to the end of the string. |
Examples
Extracting a Substring from a Literal
This extracts three characters starting from the fifth position ("Tut").
Syntax
SELECT MID("SQL Tutorial", 5, 3) AS ExtractString;
Output
Tut
Extracting from a Column
This extracts five characters from the `CustomerName` column, starting at position 2. (Assumes a `Customers` table exists with a `CustomerName` column.)
Syntax
SELECT MID(CustomerName, 2, 5) AS ExtractString
FROM Customers;
Output
ExtractString
-------------
(The five-character substring from each CustomerName, starting at position 2, will be shown here.)
Extracting from the End of a String
This extracts five characters from the end of the string.
Syntax
SELECT MID("SQL Tutorial", -5, 5) AS ExtractString;
Output
orial