Arrays y seriessolo PostgreSQL

ARRAY_APPEND

Devuelve un array con un elemento añadido al final.

Sintaxis

ARRAY_APPEND(<array>, <elemento>)
ARRAY_PREPEND(<elemento>, <array>)
<array> || <array>

Añade un elemento al final del array, ARRAY_PREPEND lo añade al principio y el operador || une dos arrays. El array original no cambia: las funciones devuelven uno nuevo. Para quitar un elemento, usa ARRAY_REMOVE.

Añadir al final y al principio
SELECT ARRAY_APPEND(ARRAY['sql', 'postgres'], 'database') AS appended,
ARRAY_PREPEND('intro', ARRAY['sql', 'postgres']) AS prepended;
appendedprepended
["sql","postgres","database"]["intro","sql","postgres"]
Unir dos arrays
SELECT ARRAY['sql', 'postgres'] || ARRAY['database', 'index'] AS combined;
combined
["sql","postgres","database","index"]
Empezar desde uno vacío
SELECT ARRAY_APPEND(ARRAY[]::text[], 'first') AS from_empty,
ARRAY_APPEND(NULL, 'first') AS from_null;
from_emptyfrom_null
["first"]["first"]

Ten en cuenta

El orden de los argumentos es distinto: ARRAY_APPEND(<array>, <elemento>), pero ARRAY_PREPEND(<elemento>, <array>). Si los confundes, ARRAY_PREPEND(ARRAY['a'], 'b') da un error poco claro: could not find array type for data type text[].

Se puede añadir a NULL: ARRAY_APPEND(NULL, 'sql') da un array de un elemento, no NULL.

Las funciones solo devuelven un array nuevo. Para cambiar los datos de una tabla, necesitas UPDATE … SET tags = ARRAY_APPEND(tags, 'sql').

Funciones relacionadas