MySQL INSERT() Function
MySQL INSERT() Function
The INSERT() string function replaces a slice of a string at a 1-based starting position with new text. Do not confuse it with the INSERT INTO SQL command that adds table rows.
Syntax
INSERT(str, pos, len, newstr)
- str: The original string to modify.
- pos: Starting 1-based character position (
1is the first character). - len: Number of characters to remove starting at
pos. - newstr: Text to place at
pos. - Return value: Modified string, or
NULLif any argument isNULL.
Setting len to 0 lets you splice newstr into the middle of str without deleting existing characters.
Practical Example
Security rules require masking the middle four digits of customer phone numbers in demo_customers before showing them to support agents.
SELECT
customer_id,
phone,
INSERT(phone, 5, 4, '****') AS masked_phone
FROM demo_customers
ORDER BY customer_id;
| customer_id | phone | masked_phone |
|---|---|---|
| 1 | 555-0192-4410 | 555-****-4410 |
| 2 | 555-8831-0029 | 555-****-0029 |
| 3 | NULL | NULL |
Here INSERT() starts at character 5, removes 4 characters (0192), and drops '****' into that exact slot.
Common Mistakes & NULL Behavior
- Position out of range returns str unchanged: If
pos <= 0orpos > CHAR_LENGTH(str),INSERT()does not raise an error or prepend text—it returns the originalstruntouched. - Using 0-based indexing: Positions start at
1. Passingpos = 0fails to modify the string at all. - Strict NULL propagation: If
str,pos,len, ornewstrisNULL, the entire call returnsNULL. - Overflowing len: If
lenexceeds the remaining length ofstr, MySQL simply replaces everything fromposthrough the end of the string.
Frequently Asked Questions
How do I insert text without deleting any characters?
Pass 0 as the len argument. For example, INSERT('ORD100', 4, 0, '-') returns 'ORD-100'.
What happens if newstr is an empty string?
INSERT(str, pos, len, '') deletes len characters starting at pos, making it handy for removing fixed-width prefixes.
When should I use REPLACE() instead of INSERT()?
Use INSERT() when you know the exact character offset. Use REPLACE() when you want to swap all matching substrings regardless of position.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.