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.

  • 1
    Do you always have only 3 items in the array or is the count dynamic? – Patrick Mevzek Aug 15 '18 at 15:58
  • It's dynamic array. – Saad Zulfiqar Aug 16 '18 at 4:41
  • 1
    If it's dynamic, what are the rules for "swapping"? – Philᵀᴹ Aug 16 '18 at 7:23
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.