Lesson

MySQL INSERT() Function

10 min reading
Free Course

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 (1 is the first character).
  • len: Number of characters to remove starting at pos.
  • newstr: Text to place at pos.
  • Return value: Modified string, or NULL if any argument is NULL.

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 <= 0 or pos > CHAR_LENGTH(str), INSERT() does not raise an error or prepend text—it returns the original str untouched.
  • Using 0-based indexing: Positions start at 1. Passing pos = 0 fails to modify the string at all.
  • Strict NULL propagation: If str, pos, len, or newstr is NULL, the entire call returns NULL.
  • Overflowing len: If len exceeds the remaining length of str, MySQL simply replaces everything from pos through 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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum