PostgreSQL – ARRAY_APPEND Function

The array_append function in PostgreSQL is used to append an element to the end of an array. It takes two arguments: the array to which you want to append an element, and the element you want to append.

Below is the syntax of the array_append function:

array_append(array, element_to_append)

Where:

array is the array to which you want to append an element.

element_to_append is the element you want to append to the array.

Here’s an example of using the array_append function:

SELECT array_append('{10, 20, 30}', 40) AS result_array;

The output would be:

result_array 
-------------- 
{10,20,30,40} 
(1 row)

In this example, the array_append function appended the value 40 to the end of the input array.

Here is another example of using the array_append function: Consider a table named cart with an array column items and you want to add a new item to all rows:

UPDATE cart 
SET items = array_append(items, 'new_item') 
WHERE some_condition;

This query will update the items arrays in the cart table, appending 'new_item' to each array that meets the specified condition.

Similar Posts