Array Column Append And Remove

Mutate array columns in place with the || append, array_remove, element assignment by index, and array_cat merges inside single UPDATE statements.

SqlData Integrity

Code

snippet
-- 数组列的就地更新:追加、删除、按位替换都在一条 UPDATE 里完成
CREATE TABLE projects (
    id     bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    owners text[] NOT NULL DEFAULT '{}'
);

INSERT INTO projects (owners) VALUES (ARRAY['ada']);

-- 追加:|| 直接连接元素
UPDATE projects SET owners = owners || 'bo' WHERE id = 1;

-- 删除指定元素(所有相等元素都会被移除)
UPDATE projects SET owners = array_remove(owners, 'ada') WHERE id = 1;

-- 按下标替换第 1 个元素(数组下标从 1 开始)
UPDATE projects SET owners[1] = 'cy' WHERE id = 1;

-- array_cat 合并两个数组,array_append 与 || 等价
UPDATE projects SET owners = array_cat(owners, ARRAY['dee']) WHERE id = 1;

How it works

Several statements share this file — INSERT / UPDATE / CREATE, with projects among the objects involved.

In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Putting it to use

The projects table is the working surface here.

Core lines

UPDATE projects SET owners = array_cat(owners, ARRAY['dee']) WHERE id = 1;
UPDATE projects SET owners = array_remove(owners, 'ada') WHERE id = 1;
UPDATE projects SET owners = owners || 'bo' WHERE id = 1;

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
The references are `projects`.