Sub topic 5
Adding, Removing, and Replacing Elements in PostgreSQL Arrays
This chapter assumes that you know basic SELECT, UPDATE, WHERE, and NULL behavior. It also assumes that posts.tags is a text[] column, such as the one below.
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags text[] NOT NULL DEFAULT '{}'
);
INSERT INTO posts (title, tags) VALUES
('Intro to arrays', ARRAY['sql', 'postgres']),
('Indexing', '{postgres,indexing,gin}');Adding elements
Use array_append to add an element at the end of an array. Use array_prepend to add one at the beginning.
UPDATE posts
SET tags = array_append(tags, 'tutorial')
WHERE id = 1;
UPDATE posts
SET tags = array_prepend('database', tags)
WHERE id = 1;After both updates, the first row has the tags database, sql, postgres, and tutorial.
You can also concatenate arrays with the || operator. This is useful when adding several values at once.
UPDATE posts
SET tags = tags || ARRAY['beginner', 'guide']
WHERE id = 1;These operations do not prevent duplicates. If tags already contains sql, appending sql adds another copy. When a value should appear at most once, test for it first.
UPDATE posts
SET tags = array_append(tags, 'tutorial')
WHERE id = 1
AND NOT tags @> ARRAY['tutorial'];The containment test asks whether the array contains the requested value. This condition is safe against adding a duplicate, although it does not clean up duplicates that already exist.
Removing elements
array_remove deletes every element equal to the value supplied as its second argument.
UPDATE posts
SET tags = array_remove(tags, 'sql')
WHERE id = 1;If tags is ['sql', 'postgres', 'sql'], the result is ['postgres']. It does not remove only the first matching element.
To remove several values, call the function more than once or concatenate a filtered array built with unnest. For a short, fixed list, repeated calls are clear:
UPDATE posts
SET tags = array_remove(
array_remove(tags, 'sql'),
'draft'
)
WHERE id = 1;If the requested value does not occur, the original array remains unchanged. Removing the only element produces an empty array, not SQL NULL.
Replacing elements
array_replace replaces every matching element.
UPDATE posts
SET tags = array_replace(tags, 'postgres', 'postgresql')
WHERE id = 1;This changes all occurrences of postgres. It is different from changing one position.
Array subscripts are 1-based, so the following changes only the second element:
UPDATE posts
SET tags[2] = 'relational'
WHERE id = 1
AND cardinality(tags) >= 2;The guard prevents the update from targeting a row without a second element. PostgreSQL can expand an array when assigning to a position beyond its current boundary, but relying on that behavior can create unexpected NULL elements. Use an explicit condition when you intend to update an existing position.
To replace a complete array, assign the new array directly:
UPDATE posts
SET tags = ARRAY['sql', 'postgresql']
WHERE id = 1;The expression on the right must have a compatible array type. An untyped literal such as '{sql,postgresql}' is usually inferred from the column, but an explicit cast can make intent clearer:
UPDATE posts
SET tags = '{sql,postgresql}'::text[]
WHERE id = 1;Choosing the operation
| Goal | Operation | Effect | Column | Column |
|---|---|---|---|---|
| Add one value at the end | `array_append(tags, value)` | Appends one element | ||
| Add one value at the beginning | `array_prepend(value, tags)` | Prepends one element | ||
| Add several values | `tags | ARRAY[...]` | Concatenates arrays | |
| Delete a value | `array_remove(tags, value)` | Removes every match | ||
| Rename a value | `array_replace(tags, old, new)` | Replaces every match | ||
| Change one position | `tags[position] = value` | Updates one subscript |
How an array update works
An array expression is evaluated from the old row value, then the resulting array is stored in the updated row.
This means that two concurrent updates to the same row can overwrite each other if each session reads an old array and then writes a derived array. Use a transaction and appropriate locking when multiple sessions may modify the same row.
Exercise
Write an UPDATE statement that adds featured to post 2 only when that tag is not already present.
Show answer
UPDATE posts SET tags = array_append(tags, 'featured') WHERE id = 2 AND NOT tags @> ARRAY['featured'];