Re: Calling set-returning functions in a non-set-expecting context

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Jan Behrens <jbe-mlist(at)magnetkern(dot)de>
Cc: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Calling set-returning functions in a non-set-expecting context
Date: 2025-02-17 17:33:36
Message-ID: 849267.1739813616@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Jan Behrens <jbe-mlist(at)magnetkern(dot)de> writes:
> I wonder if it is guaranteed that when calling a set-returning function
> in a non-set-expecting context, the used row is guaranteed to be the
> first row returned.

In general, I'd expect either we'd use the first row or throw an
error. We're not 100% consistent about which rule applies, but
I can't think of a reason for anything to do something else.

> I.e. if I have the following function definition
> CREATE FUNCTION foo() RETURNS INTEGER RETURN generate_series(1, 10);
> is it then guaranteed, that foo() always returns 1? And if so, is that
> documented somewhere? I didn't find it.

I'd say that using the first row (and not throwing an error) is
guaranteed for the specific case of SQL-language functions by the same
text you quote:

> "SQL functions execute an arbitrary list of SQL statements, returning
> the result of the last query in the list. In the simple (non-set) case,
> the first row of the last query's result will be returned. (Bear in
> mind that 'the first row' of a multirow result is not well-defined
> unless you use ORDER BY.) If the last query happens to return no rows
> at all, the null value will be returned."

The reason for the parenthetical weasel-wording is that a query might
require joins, aggregation, etc, and some of our implementations of
those things don't preserve row order. If we're talking about a
simple invocation of another set-returning function, it's just
going to take whatever that function returns first.

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Ayush Vatsa 2025-02-17 18:01:46 Clarification on Role Access Rights to Table Indexes
Previous Message Jan Behrens 2025-02-17 16:51:48 Calling set-returning functions in a non-set-expecting context