// strings reference

SQL OVERLAY function

Replaces part of a string with a new substring at a given 1-based position, in one standard-syntax call.

Categoría
Strings
Returns
string
In this category
101 of 172

Sintaxis

OVERLAY(str PLACING new_str FROM start)
OVERLAY(str PLACING new_str FROM start FOR count)

Each block is a separate form. The support table and the examples show which engine takes which.

Soporte del motor

MotorSupportNotas
SQL Server Different name or syntax Use STUFF(str, start, len, new).
PostgreSQL Sí Supported under this name.
MySQL Different name or syntax Use INSERT(str, pos, len, new).
SQLite Not built in No OVERLAY; splice with SUBSTR and ||.
Oracle Not built in No OVERLAY; splice with SUBSTR and ||.

Ejemplos

PostgreSQL

SELECT OVERLAY('abcdef' PLACING 'XY' FROM 2 FOR 3) AS result;  -- aXYef

PostgreSQL

SELECT OVERLAY(card PLACING '****' FROM 8 FOR 4) AS masked
FROM payments;

Conviene saberlo

  • FOR defaults to the length of the replacement: OVERLAY('abcdef' PLACING 'XY' FROM 2) replaces two characters and returns 'aXYdef'.
  • OVERLAY is in the SQL standard, but PostgreSQL is the only engine of these five that implements it. It also works on bytea and bit strings.
  • FOR 0 is a pure insert: OVERLAY('abc' PLACING 'X' FROM 2 FOR 0) is 'aXbc'.

Questions about OVERLAY

What does the FOR clause change?

How many original characters are removed. Without FOR, the replacement's own length decides; with FOR 4, exactly four characters go, whatever the replacement's length.

What is the SQL Server equivalent?

STUFF(str, start, count, new) does the same delete-and-insert with the same 1-based positions.

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.