Posted almost 5 years ago. Visible to the public. Linked content.

PostgreSQL: How to add/remove/modify array values (and how to replace 1 value with multiple values)

PostgreSQL's array data type is pretty useful, but manipulating values of arrays can be awkward because of its syntax.

Consider the following users table which each example below will start from:

name topics
Alice {cats,dogs}
Bob {llamas}

(PostgreSQL uses curly braces to represent arrays, true story.)

Adding values

Use the array_cat function, or the || operator.

These calls will add the values "cats" and "mice" to users.topics:

UPDATE users SET topics = array_cat(topics, '{cats,mice}');

UPDATE users SET topics = topics || '{cats,mice}';

Note that this may produce duplicates.

name topics
Alice {cats,dogs,cats,mice}
Bob {llamas,cats,mice}

Removing values

Use the array_remove function (Postgres 9.2+) to remove 1 value from the array (all its occurences, should it appear more than once):

UPDATE users SET topics = array_remove(topics, 'cats');
name topics
Alice {dogs}
Bob {llamas}

Replacing values

Postgres 9.3+ offers array_replace. It will find 1 value (again all occurences) and replace it with 1 given other value.

UPDATE users SET topics = array_replace(topics, 'dogs', 'mice');
name topics
Alice {cats,mice}
Bob {llamas}

Replacing multiple values

To replace multiple values, you need to combine what you learned above as array_replace won't do the trick. Here is one way:

UPDATE users SET topics = array_remove(topics, 'cats') || '{mice,pandas}' WHERE topics @> ARRAY['cats'];

Note the condition. It's important as we want to append "mice" and "pandas" only to those arrays that include "cats" in the first place.

name topics
Alice {dogs,mice,pandas}
Bob {llamas}

Notes on working with String arrays in PostgreSQL

  • Prefer the '{one,two}' syntax. If you use the ARRAY[] syntax, you'll need to add a type in order to perform operations with e.g. a string array column: ARRAY['one', 'two']::varchar[].
  • Avoid working with plain strings, always wrap them as arrays when you are working with arrays. E.g. bad: WHERE topics @> 'value', better: WHERE topics @> '{value}'

Check the PostgreSQL documentation on Array Functions and Operators for more information, and other useful functions.

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Arne Hartherz
Last edit:
over 1 year ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more