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.
Code
-- 数组列的就地更新:追加、删除、按位替换都在一条 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which tables does this file reference?
- The references are `projects`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.