MySQL INSERT() Function
The INSERT()
function in MySQL modifies a string by inserting a new substring at a specific position and optionally replacing a portion of the existing string.
INSERT(): Definition and Usage
INSERT()
is a very useful tool for precise string manipulation. Unlike REPLACE()
, which replaces all occurrences of a substring, INSERT()
targets a specific location within the string. You specify the original string, the starting position for the insertion, the number of characters to replace (from the original string), and the new substring to be inserted. The starting position is 1-based (the first character is position 1).
Syntax
Syntax
INSERT(string, position, number, string2)
Parameter Values
Parameter | Description |
---|---|
string |
The original string to be modified. This is required. |
position |
The starting position for the insertion (1-based index). This is required. |
number |
The number of characters to replace in the original string. This is required. |
string2 |
The new string to insert. This is required. |
Examples
Replacing Characters in a String
This replaces the first nine characters of "W3Schools.com" with "Example".
Syntax
SELECT INSERT("W3Schools.com", 1, 9, "Example");
Output
Example.com
Inserting into a String
This inserts "no" starting at position 11, replacing three characters.
Syntax
SELECT INSERT("W3Schools.com", 11, 3, "no");
Output
W3Schools.no