PostgreSQL array_replace() Function
The PostgreSQL array_replace() function replaces the specified element with a new element in the specified array and returns the modified array.
array_replace() Syntax
Here is the syntax of the PostgreSQL array_replace() function:
array_replace(array, from_element, to_element) -> array
Parameters
array-
Required. The array to replace the element from.
from_element-
Required. The element to be replaced.
to_element-
Required. The element to replace with.
Return value
The PostgreSQL function array_replace() function replaces the specified element with a new element in the specified array and returns the modified array.
The type of to_element and from_element must be the same as the data type of the array, otherwise the array_replace() function will give an error message.
The array_replace() function will return NULL if the specified array is NULL.
array_replace() Examples
This example shows how to use the PostgreSQL array_replace() function to replace all 2 with 1 in the array [1, 1, 2, 1, 2, 1, 2].
SELECT array_replace(ARRAY[1, 1, 2, 1, 2, 1, 2], 2, 1);
array_replace
-----------------
{1,1,1,1,1,1,1}