Sub topic 5
Adding, removing, and replacing elements
What this chapter assumes
You should be comfortable with SELECT, INSERT, UPDATE, and WHERE. You should know how to declare an array column and write array values with ARRAY[...] and '{...}'. You should also know that subscripts start at 1 and that NULL follows three-valued logic. This chapter covers the write side of arrays: changing the contents of an existing array value.
The examples use the posts table from earlier in the tutorial. Run this setup first. It drops and recreates the table so the ids below are predictable.
DROP TABLE IF EXISTS posts;
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}');Arrays are replaced, not edited in place
PostgreSQL has no "push" or "pop" that mutates a stored array. Every function in this chapter takes an array and returns a new array. An UPDATE then writes that new value back to the column, so the whole array is rewritten each time.
This has two consequences:
- You always write the change as
SET tags = <expression that returns an array>. - The cost of an update grows with the array's size, because the full array is stored again as part of the new row version. Large arrays that change often are a warning sign, which the last section returns to.
The diagram maps what you want to do to the tool that does it.
Adding elements
array_append, array_prepend, and ||
array_append(array, element) adds to the end. array_prepend(element, array) adds to the front. Note that the element comes first in array_prepend.
UPDATE posts
SET tags = array_append(tags, 'tutorial')
WHERE id = 1
RETURNING id, tags;
-- id=1 tags={sql,postgres,tutorial}
UPDATE posts
SET tags = array_prepend('featured', tags)
WHERE id = 1
RETURNING id, tags;
-- id=1 tags={featured,sql,postgres,tutorial}The || operator does the same work. tags || 'x'::text appends, 'x'::text || tags prepends, and tags || other_array concatenates two arrays. The operator is shorter, but with an untyped literal on one side the parser has to guess whether you mean an element or an array. Cast the literal ('x'::text) or use the named functions when you want no doubt.
Concatenating arrays
array_cat(a, b) and a || b join two arrays end to end. Duplicates are kept.
SELECT array_cat(ARRAY[1, 2], ARRAY[2, 3]) AS joined;
-- {1,2,2,3}Adding only when the value is missing
Appending never checks for duplicates. Run array_append(tags, 'tutorial') twice and you get two copies. To keep the array set-like, guard the update with a containment test.
UPDATE posts
SET tags = array_append(tags, 'tutorial')
WHERE id = 1
AND NOT tags @> ARRAY['tutorial'];If the tag is already there, the WHERE clause matches no row and nothing is written. That also avoids producing a new row version for no reason. The statement is safe to run repeatedly.
Assigning past the end
You can also assign directly to a subscript. If the position is beyond the current end, PostgreSQL extends the array and fills the gap with NULL.
UPDATE posts
SET tags[5] = 'extra'
WHERE id = 2
RETURNING tags;
-- {postgres,indexing,gin,NULL,extra}Position 4 is now a NULL element. This is rarely what you want, so prefer array_append unless you really are filling specific slots. Assigning to position 0 or a negative position on a non-empty array is worse. It succeeds but gives the array a lower bound other than 1, such as [0:3]={...}. Later subscript code that assumes 1-based positions will then read the wrong elements.
Removing elements
array_remove removes by value
array_remove(array, value) returns the array without any element equal to value. It removes every match, not only the first.
UPDATE posts
SET tags = array_remove(tags, 'sql')
WHERE id = 1
RETURNING tags;
-- {featured,postgres,tutorial}If the value is not present, the array comes back unchanged. The comparison treats NULL as equal to NULL, so array_remove(ARRAY[1, NULL, 2], NULL) returns {1,2}. That is a handy way to strip NULL elements, which the plain = operator could not do.
array_remove only works on one-dimensional arrays. Calling it on a multidimensional array raises an error.
Removing by position
There is no array_remove_at. Build the result from two slices that skip the position you want to drop. Omitting a slice bound means "from the start" or "to the end".
-- Drop the element at position 2
UPDATE posts
SET tags = tags[:1] || tags[3:]
WHERE id = 2
RETURNING tags;
-- {postgres,gin,NULL,extra}Slices that fall outside the array return an empty array rather than an error. A position past the end therefore leaves the array unchanged. This pattern assumes the array starts at subscript 1.
Removing several values at once
Nesting array_remove calls works for two or three values. For a longer list, rebuild the array from a filtered unnest. WITH ORDINALITY preserves the original order.
UPDATE posts
SET tags = ARRAY(
SELECT u.t
FROM unnest(tags) WITH ORDINALITY AS u(t, p)
WHERE u.t <> ALL (ARRAY['postgres', 'gin'])
ORDER BY u.p
)
WHERE tags && ARRAY['postgres', 'gin'];Two details matter here. First, <> ALL evaluates to NULL for a NULL element, and WHERE discards NULL, so this form also drops NULL elements. Write u.t IS NULL OR u.t <> ALL (...) if you need to keep them. Second, the WHERE tags && ... filter on the UPDATE skips rows that have nothing to remove.
Replacing elements
array_replace replaces by value
array_replace(array, old, new) swaps every element equal to old for new. Like array_remove, it treats NULL as equal to NULL.
UPDATE posts
SET tags = array_replace(tags, 'postgres', 'postgresql')
WHERE tags @> ARRAY['postgres'];This is a common way to rename a tag across every row. Because it replaces all matches, an array that already holds both postgres and postgresql ends up with two postgresql entries. Deduplicate afterwards if that matters.
Replacing by position
Assign to a subscript to replace one element, or to a slice to replace several.
UPDATE posts
SET tags[1] = 'start-here'
WHERE id = 1;
UPDATE posts
SET tags[2:3] = ARRAY['a', 'b']
WHERE id = 1
RETURNING tags;For slice assignment, the right-hand array must supply at least as many elements as the slice covers, or PostgreSQL raises an error. You can set several elements in one statement, such as SET tags[1] = 'x', tags[2] = 'y'. Assigning to the same column twice in a single SET list is not allowed with ordinary column names, but subscripted targets are permitted.
NULL handling at a glance
The table shows what each function returns when the array itself is NULL or contains NULL. The tags column in this tutorial is NOT NULL, but arrays from other columns or expressions may not be.
| Expression | Result |
|---|---|
| `array_append(NULL::text[], 'x')` | `{x}` (a NULL array is treated as empty) |
| `array_cat(NULL::text[], ARRAY['x'])` | `{x}` |
| `array_remove(NULL::text[], 'x')` | NULL |
| `array_replace(NULL::text[], 'x', 'y')` | NULL |
| `array_remove(ARRAY['a', NULL], NULL)` | `{a}` |
| `array_append(ARRAY['a'], NULL)` | `{a,NULL}` (a NULL element is added) |
The first two rows are why appending to a nullable column "just works", while removing from the same column leaves NULL as NULL. If a column allows NULL and you want one consistent meaning, declare it NOT NULL DEFAULT '{}' as the posts table does.
Concurrency and cost
Compute the new array inside SQL, as in every example above. Do not read the array into application code, change it there, and write it back. Two clients doing that at the same time will each start from the same old value, and the second write overwrites the first.
A single UPDATE ... SET tags = array_append(tags, ...) is safer. Under the default READ COMMITTED isolation level, if another transaction changes the row first, PostgreSQL waits for it to finish, re-reads the newest version of the row, and re-evaluates both the WHERE clause and the SET expression. The guarded add from earlier therefore stays correct under concurrent callers.
Cost is the other limit. Every update writes a complete new row version, and large arrays are stored out of line, so a long array that changes often produces much more write traffic than a one-row insert into a related table would. The final chapter weighs this against the convenience of arrays.
Common errors
- Duplicates after appending.
array_appendnever deduplicates. Guard withNOT tags @> ARRAY[...]. - Argument order in
array_prepend. The element comes first and the array second. Swapping them gives a type error or a wrong result. - Unexpected NULL elements. Assigning past the end fills the gap with NULL. Later
= ANYtests against such arrays can return NULL instead of false. - Lower bound not 1. Assigning to position 0 or below shifts the bounds, and slice-based removal then picks the wrong elements.
- Untyped literal with
||. The parser may read'x'as an array literal. Cast it, or callarray_append. - Removing from a multidimensional array.
array_removesupports one dimension only.
Exercise
The row with id = 2 currently has tags = {postgres,indexing,gin}. Write one UPDATE that renames the tag 'indexing' to 'indexes' and then appends 'reviewed', but only if 'reviewed' is not already present afterwards. What does the tags column hold after the statement, and why is it safe to run twice?
Show answer
UPDATE posts SET tags = arrayappend(arrayreplace(tags, 'indexing', 'indexes'), 'reviewed') WHERE id = 2 AND NOT tags @> ARRAY['reviewed']; After the first run, tags is {postgres,indexes,gin,reviewed}. On a second run the WHERE clause is false because tags already contains 'reviewed', so no row is updated and the column does not change. If 'indexing' were also still present on a row that already had 'reviewed', that row would be skipped as well, so the guard should be adjusted when the rename must happen independently of the append.
Exercise
Write an expression that removes the element at position 3 from a one-dimensional array column named tags, and explain what it returns when the array has only two elements.
Show answer
tags[:2] || tags[4:]. The first slice keeps positions 1 and 2, and the second slice keeps everything from position 4 onward. With only two elements, tags[4:] is an empty array and tags[:2] is the whole array, so the result is the unchanged two-element array. Out-of-range slices return an empty array instead of raising an error.