Remove array values in pgSQL

Viewed 46189

Is there a way to remove a value from an array in pgSQL? Or to be more precise, to pop the last value? Judging by this list the answer seems to be no. I can get the result I want with an additional index pointer, but it's a bit cumbersome.

10 Answers

No, I don't think you can. At least not without writing something ugly like:

SELECT ARRAY (
 SELECT UNNEST(yourarray) LIMIT (
  SELECT array_upper(yourarray, 1) - 1
 )
)

I'm not sure about your context, but this should give you something to work with:

CREATE TABLE test (x INT[]);
INSERT INTO test VALUES ('{1,2,3,4,5}');

SELECT x AS array_pre_pop,
       x[array_lower(x,1) : array_upper(x,1)-1] AS array_post_pop, 
       x[array_upper(x,1)] AS popped_value 
FROM test;


 array_pre_pop | array_post_pop | popped_value 
---------------+----------------+--------------
 {1,2,3,4,5}   | {1,2,3,4}      |            5
Related