Aliasing syntax question

Started by Kevin Murphyabout 17 years ago2 messagesgeneral
Jump to latest
#1Kevin Murphy
murphy@genome.chop.edu

I've now seen the 'unnest' function defined in a few different ways with
regard to aliases.

Substitute the following pairs of values for X and Y in the query below,
and all of them work (in PG 8.3.6, at least):

X Y
g g
i g(i)
g g(i)
g.i g(i)

create or replace function unnest(anyarray)
returns setof anyelement as $$
select $1[X] from generate_series(array_lower($1,1),array_upper($1,1)) Y;
$$ language sql;

Please enlighten the unworthy!

Thanks,
Kevin Murphy

#2Tom Lane
tgl@sss.pgh.pa.us
In reply to: Kevin Murphy (#1)
Re: Aliasing syntax question

Kevin Murphy <murphy@genome.chop.edu> writes:

Substitute the following pairs of values for X and Y in the query below,
and all of them work (in PG 8.3.6, at least):

X Y
g g
i g(i)
g g(i)
g.i g(i)

create or replace function unnest(anyarray)
returns setof anyelement as $$
select $1[X] from generate_series(array_lower($1,1),array_upper($1,1)) Y;
$$ language sql;

The reason they all work is that generate_series() returns a scalar
(ie, an integer). In all these cases the table alias "g" would
resolve as the function's whole-tuple result, but that's just an
integer. We also provide a column alias for the scalar value,
which is why cases 2 and 4 work.

In case 1 the alias Y is really being read as g(g), so you could also
have written X as g.g if you like being pedantic. I think BTW that the
unqualified reference to g will be resolved preferentially as being a
column alias not a table alias, but you end up at the same result either
way for a scalar function.

regards, tom lane