Your statement (augmented with the missing FROM
clause):
SELECT array_replace(col1, 1, 100) FROM tbl WHERE id = 1;
As commented by @mu, array_replace()
was introduced with pg 9.3. I see 3 options for older versions:
As long as ...
- we are dealing with integer arrays.
- elements are unique.
- and the order of elements is irrelevant.
A simple and fast option would be to install the additional module intarray
, which (among other things) provides operators to subtract and add elements (or whole arrays) from/to integer arrays:
SELECT CASE col1 && '{1}'::int[] THEN (col1 - 1) + 100 ELSE col1 END AS col1
FROM tbl WHERE id = 1;
2. Emulate with SQL functions
A (slower) drop-in replacement for array_replace()
using polymorphic types, so it works for any base type:
CREATE OR REPLACE FUNCTION f_array_replace(anyarray, anyelement, anyelement)
RETURNS anyarray LANGUAGE SQL IMMUTABLE AS
'SELECT ARRAY (SELECT CASE WHEN x = $2 THEN $3 ELSE x END FROM unnest($1) x)';
Does not replace NULL values. Related:
If you need to guarantee order of elements:
3. Apply patch to source and recompile
Get the patch "Add array_remove() and array_replace() functions" from the git repo, apply it to the source of your version and recompile. May or may not apply cleanly. The older your version the worse are your chances. I have not tried that, I would rather upgrade to the current version.