An array element can be accessed via an index; if the array does not contain an element for this index, the NULL value is returned, as shown in the following example:
CREATE TABLE color(
color text []
);
INSERT INTO color(color) VALUES ('{red, green}'::text[]);
INSERT INTO color(color) VALUES ('{red}'::text[]);
To confirm that NULL is returned, let's run the following:
car_portal=> SELECT color [3]IS NOT DISTINCT FROM null FROM color;
?column?
----------
t
t
(2 rows)
Also, an array can be sliced by providing a lower and upper bound, as follows:
car_portal=> SELECT color [1:2] FROM color;
color
-------------
{red,green}
{red}
(2 rows)
When updating an array, one could completely replace the array, get a slice, replace an element, or append the array using the || concatenation operator as shown in the below example. The full set of array functions can be found at: https://www.postgresql.org/docs/current/static/functions-array.html-
car_portal=> SELECT ARRAY ['red', 'green'] || '{blue}'::text[] AS append;
append
------------------
{red,green,blue}
(1 row)
Time: 0,848 ms
car_portal=> UPDATE color SET color[1:2] = '{black, white}';
UPDATE 2
car_portal=> table color ;
color
---------------
{black,white}
{black,white}
(2 rows)
The array_remove function can be used to remove all the elements that are equal to a certain value, as follows:
car_portal=> SELECT array_remove ('{Hello, Hello, World}'::TEXT[], 'Hello');
array_remove
--------------
{World}
(1 row)
To remove a certain value based on an index, one can use the WITH ORDINALITY clause. So, let's assume that we want to remove the first element of an array; this can be achieved as follows:
car_portal=> SELECT ARRAY(SELECT unnest FROM unnest ('{Hello1, Hello2, World}'::TEXT[]) WITH ordinality WHERE ordinality <> 1);
array
----------------
{Hello2,World}
(1 row)