How to Modify Arrays

Postgres provides several functions to introduce changes to an existing array. Perhaps the main two functions are array_remove which allows you to remove an element by giving the value of the element and the function array_replace which can be used to modify an element by giving the old and the new values. Let’s see some examples.

Let’s remove the element ‘banana’ from the array

update array_example set fruits = array_remove(fruits, ‘banana’);
 
select fruits from array_example;
fruits text[]
{grape,apple,orange,peach}

Let’s change the value of ‘apple’ to ‘red apple’

update array_example set fruits = array_replace(fruits, ‘apple’, ‘red apple’);
 
select fruits from array_example;
fruits text[]
{grape,red apple,orange,peach}

IN THIS PAGE