In PostgreSQL, we can use the array_append()
function to append an element to the end of an array.
The first argument is the array, and the second argument is the element to append.
Example
Here’s an example to demonstrate:
SELECT array_append(array['Cat', 'Dog'], 'Buffalo');
Result:
{Cat,Dog,Buffalo}
In this case I appended Buffalo
to the array.
Here’s a database example:
SELECT
c2,
array_append(c2, 6)
FROM t1
WHERE c1 = 1;
Result:
c2 | array_append
-------------+---------------
{1,2,3,4,5} | {1,2,3,4,5,6}
Concatenation Equivalent
The array_append()
function does the same thing that the ||
operator does when we use the array to the left of the operator, and the new element to the right.
Therefore, we could rewrite the previous example as follows:
SELECT
c2,
c2 || 6 AS "Concatenated"
FROM t1
WHERE c1 = 1;
Result:
c2 | Concatenated
-------------+---------------
{1,2,3,4,5} | {1,2,3,4,5,6}
Prepending Elements
There’s also an array_prepend()
function that prepends elements to the start of the array. This function requires the arguments in the opposite order to array_append()
; the new element comes first, followed by the array. The array_prepend()
function is just like using the ||
operator with the new element to the left of the operator, and the array to the right.