// strings reference

SQL INSERT (string) function

MySQL string splicing: removes len characters at a 1-based position and inserts a replacement string there.

类别
Strings
Returns
string
In this category
102 of 172

语法

INSERT(str, pos, len, new_str)

引擎支持

引擎Support备注
SQL Server Different name or syntax Use STUFF(str, start, len, new).
PostgreSQL Different name or syntax Use OVERLAY(str PLACING new FROM start FOR len).
MySQL 是 Supported under this name.
SQLite Not built in No INSERT function; splice with SUBSTR and ||.
Oracle Not built in No INSERT function; splice with SUBSTR and ||.

示例

MySQL

SELECT INSERT('abcdef', 2, 3, 'XY') AS result;  -- aXYef

MySQL

SELECT INSERT(card, 8, 4, '****') AS masked
FROM payments;

值得了解

  • The name collides with the INSERT statement; MySQL tells them apart by position, so INSERT(...) inside an expression is always the string function.
  • A pos outside the string (0, negative, or past the end) returns the original string unchanged, so INSERT cannot append.
  • A len of 0 is a pure insert; a len longer than the rest of the string replaces everything from pos to the end: INSERT('abc', 2, 99, 'X') is 'aX'. Any NULL argument returns NULL.

Questions about INSERT

Is INSERT(str, pos, len, new) related to INSERT INTO?

No. The function edits a string value; the statement adds rows.

What is the SQL Server equivalent?

STUFF(str, pos, len, new), with the same pure insert at len 0. Out-of-range positions differ: STUFF returns NULL, INSERT returns the input.

What happens when pos is larger than the string?

MySQL returns the original string unchanged instead of appending. Use CONCAT to add text at the end.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.