element from an array by its index

Started by Murat Kabilovalmost 17 years ago4 messagesgeneral
Jump to latest
#1Murat Kabilov
kabilovmf@gmail.com

Hello,

I would like to know if there is a function that extracts an element by its
index from an array?

#2Sam Mason
sam@samason.me.uk
In reply to: Murat Kabilov (#1)
Re: element from an array by its index

On Tue, Jul 21, 2009 at 04:08:51PM +0600, Murat Kabilov wrote:

I would like to know if there is a function that extracts an element by its
index from an array?

No, the syntax most people expect and use would be arr[ndx]. If you
want a function, it would be easy to do:

CREATE FUNCTION array_index(anyarray,int)
RETURNS anyelement IMMUTABLE
LANGUAGE sql AS $$
SELECT $1[$2]; $$;

--
Sam http://samason.me.uk/

#3Merlin Moncure
mmoncure@gmail.com
In reply to: Sam Mason (#2)
Re: element from an array by its index

On Tue, Jul 21, 2009 at 10:47 AM, Sam Mason<sam@samason.me.uk> wrote:

On Tue, Jul 21, 2009 at 04:08:51PM +0600, Murat Kabilov wrote:

I would like to know if there is a function that extracts an element by its
index from an array?

No, the syntax most people expect and use would be arr[ndx].  If you
want a function, it would be easy to do:

 CREATE FUNCTION array_index(anyarray,int)
     RETURNS anyelement IMMUTABLE
     LANGUAGE sql AS $$
   SELECT $1[$2]; $$;

but, why would you write a function to do this?

merlin

#4Sam Mason
sam@samason.me.uk
In reply to: Merlin Moncure (#3)
Re: element from an array by its index

On Tue, Jul 21, 2009 at 02:29:12PM -0400, Merlin Moncure wrote:

On Tue, Jul 21, 2009 at 10:47 AM, Sam Mason<sam@samason.me.uk> wrote:

On Tue, Jul 21, 2009 at 04:08:51PM +0600, Murat Kabilov wrote:

I would like to know if there is a function that extracts an element by its
index from an array?

No, the syntax most people expect and use would be arr[ndx]. If you
want a function, it would be easy to do:

CREATE FUNCTION array_index(anyarray,int)
RETURNS anyelement IMMUTABLE
LANGUAGE sql AS $$
SELECT $1[$2]; $$;

but, why would you write a function to do this?

No idea, my guess was that Murat is driving PG through some other code
and this expected to generate function-call style syntax for everything,
including array indexing.

I'd be interested to know the real reason as well!

--
Sam http://samason.me.uk/