PostgreSQL – OVERLAY Function

The OVERLAY function is used to replace a portion of a string with another string. It allows you to specify the position within the original string where the replacement should start and the length of the portion to replace.

Here’s the basic syntax of the OVERLAY function:

OVERLAY(string1 PLACING string2 FROM start_position [FOR length])
  • string1: The original string in which you want to replace a portion.
  • string2: The string that you want to insert into string1.
  • start_position: The position in string1 where the replacement should begin. The position is 1-based, meaning the first character is at position 1.
  • length (optional): The number of characters to replace. If not specified, the entire portion starting from start_position will be replaced.

Here’s an example of how to use the OVERLAY function:

SELECT OVERLAY('This is a test.' PLACING 'not ' FROM 6 FOR 2);

This query will replace the portion of the string starting from position 6 (which is the space character after “is”) and lasting for 2 characters with the string “not “. So, the result will be “This is not a test.”

You can also use column values from a table as input for the OVERLAY function:

SELECT OVERLAY(column_name PLACING 'replacement' FROM start_position FOR length) FROM your_table;

Replace column_name, start_position, length, and 'replacement' with the appropriate values for your specific use case.

The OVERLAY function is useful for modifying strings within your database queries, and it provides flexibility for replacing specific portions of text.

Similar Posts