// conversion reference

SQL ARRAY_APPEND function

array_append(tags, 'sql') returns the array with one more element. The || operator does the same, but an untyped string literal on its right is read as an array.

カテゴリ
Conversion
Returns
array
In this category
27 of 39

構文

ARRAY_APPEND(array, element)
array || element
array || array

Each block is a separate form. The support table and the examples show which engine takes which.

エンジンサポート

エンジンSupportメモ
SQL Server Not built in No built-in equivalent.
PostgreSQL はい array_append, array_prepend, array_cat, ||
MySQL Not built in no array type; JSON_ARRAY_APPEND for JSON
SQLite Not built in no array type; json functions for JSON
Oracle Not built in collection procedures in PL/SQL, not SQL functions

例

PostgreSQL

UPDATE articles
SET tags = array_append(tags, 'sql');

PostgreSQL

UPDATE articles SET tags = tags || 'db'::text;

PostgreSQL

SELECT ARRAY_CAT(ARRAY['a'], ARRAY['b']) AS both;

知っておくと便利なこと

  • || is overloaded: array || element appends, array || array concatenates, element || array prepends. With an untyped literal, PostgreSQL tries the array form: tags || 'db' fails with 'malformed array literal: "db"'. Write tags || 'db'::text or use array_append.
  • An append rewrites the full array value on every UPDATE; append-heavy workloads on wide arrays behave better as a child table or a jsonb column.
  • A NULL array is treated as empty here: array_append(NULL::text[], 'a') is {a}, and so is NULL::text[] || 'a'::text. That differs from most SQL functions, where NULL in means NULL out.

Questions about ARRAY_APPEND

How do I prepend instead?

array_prepend(x, a), or the reversed ||: x || a puts the scalar in front. The function names are unambiguous; the operator's meaning depends on side.

Why does tags || 'db' say malformed array literal?

The literal 'db' has no type yet, and PostgreSQL resolves it as text[] to match the array || array operator. Cast it, 'db'::text, or call array_append(tags, 'db').

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.