Support for negative index values in array fetching - Mailing list pgsql-hackers

From Valtonen, Hannu
Subject Support for negative index values in array fetching
Date
Msg-id 4D205749.6040704@hut.fi
Whole thread Raw
Responses Re: Support for negative index values in array fetching  (Florian Pflug <fgp@phlo.org>)
List pgsql-hackers
Hi,

I ran into the problem of getting the last n elements out of an array
and while some workarounds do exist:
(http://stackoverflow.com/questions/2949881/getting-the-last-element-of-a-postgres-array-declaratively)
I was still annoyed that I couldn't just ask for the last n values in an
array Python/Perl style.

Here's a patch to add support for negative index values in fetching
elements from an array.

i.e.

postgres=# CREATE TABLE blah (a int[]);
CREATE TABLE
Time: 11.357 ms
postgres=# INSERT INTO blah (a) VALUES (ARRAY[1,2,3,4,5,6,7,8,9,10]);
INSERT 0 1
Time: 1.282 ms
postgres=# SELECT a[-1] FROM blah;
  a
----
  10
(1 row)

Time: 0.450 ms
postgres=# SELECT a[-5:10] FROM blah;
       a
--------------
  {6,7,8,9,10}
(1 row)

Time: 0.949 ms

While testing this I BTW ran into funny behaviour in setting array
slices, as in:

postgres=# update blah set a[-5] = 12;
UPDATE 1
Time: 1.500 ms
postgres=# select * from blah;
                              a
------------------------------------------------------------
  [-5:10]={12,NULL,NULL,NULL,NULL,NULL,1,2,3,4,5,6,7,8,9,10}
(1 row)

Time: 0.431 ms

And since this negative array expansion behaviour totally surprised me,
I haven't changed that in this patch at all.

--
Hannu Valtonen



Attachment

pgsql-hackers by date:

Previous
From: Simon Riggs
Date:
Subject: Re: Sync Rep Design
Next
From: Dimitri Fontaine
Date:
Subject: Re: Extension upgrade, patch v0: debug help needed