// strings reference

SQL STUFF function

Position-based edit: delete len characters starting at pos, then insert the replacement into the gap. Value-based REPLACE's positional sibling.

Catégorie
Strings
Returns
string
In this category
61 of 172

Syntaxe

STUFF(string, pos, len, new_string)

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Oui Supported under this name.
PostgreSQL Different name or syntax overlay(s placing new FROM pos FOR len)
MySQL Different name or syntax INSERT(s, pos, len, new)
SQLite Not built in No built-in equivalent.
Oracle Not built in No built-in equivalent.

Exemples

SQL Server

SELECT STUFF('abcdef', 3, 2, 'XY') AS spliced;  -- abXYef

PostgreSQL

SELECT overlay('abcdef' placing 'XY' from 3 for 2) AS spliced;  -- abXYef

MySQL

SELECT INSERT('abcdef', 3, 2, 'XY') AS spliced;  -- abXYef

Bon à savoir

  • Positions are 1-based. SQL Server returns NULL when pos is 0, negative, or past the last character (so STUFF cannot append), or when len is negative. len 0 means pure insertion, and a NULL replacement means pure deletion: STUFF('abc', 2, 1, NULL) is 'ac'.
  • PostgreSQL's overlay(s placing 'XY' FROM 3 FOR 2) and MySQL's INSERT(s, 3, 2, 'XY') do the same job, but edge cases differ: MySQL's INSERT returns the original string when pos is out of range instead of NULL.
  • It is not REPLACE: STUFF edits by coordinates, REPLACE by value, and TRANSLATE character by character.
  • Formatting idioms: STUFF(phone, 4, 0, '-') inserts dashes without deleting anything.

Questions about STUFF

What does len = 0 do in STUFF?

Nothing is deleted: the replacement is inserted at the position. STUFF('abc', 2, 0, 'X') gives 'aXbc', the standard insert-at-position idiom.

Why does MySQL's INSERT return the whole string?

MySQL's INSERT(str, pos, len, new) returns the original unchanged when pos is outside the string, while SQL Server's STUFF returns NULL. Different edge semantics for the same shape.

Is STUFF available outside SQL Server?

Not by name. PostgreSQL's overlay() and MySQL's INSERT() are the equivalents; Oracle and SQLite hand-roll with SUBSTR concatenation.

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL.

// 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.