0

How to swap array values in PostgreSQL. For example i have a table that has a column whose data type is bigint[]. It has following value in it.

value: {111, 222, 333} My desired output is {333, 111, 222}

i can not find any built in function to achieve other than array_replace.

3
  • 1
    Do you always have only 3 items in the array or is the count dynamic? Commented Aug 15, 2018 at 15:58
  • It's dynamic array. Commented Aug 16, 2018 at 4:41
  • 1
    If it's dynamic, what are the rules for "swapping"? Commented Aug 16, 2018 at 7:23

1 Answer 1

1

You can access the values by index, as follows:

postgres=# create table intarray ( aaa int8[] ) ;
CREATE TABLE
postgres=# insert into intarray values ( ARRAY [ 111, 222, 333 ]  ) ;
INSERT 0 1
postgres=# select * from intarray;
      aaa      
---------------
 {111,222,333}
(1 row)

postgres=# select aaa[3],aaa[2],aaa[1] from intarray;
 aaa | aaa | aaa 
-----+-----+-----
 333 | 222 | 111
(1 row)

postgres=# select ARRAY[aaa[3],aaa[1],aaa[2]] from intarray;
     array     
---------------
 {333,111,222}
(1 row)

postgres=# 

Reading the documentation may help you.

1
  • It's dynamic array. Commented Aug 16, 2018 at 4:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.