Returning from a PL/pgSQL function
You can mix RETURN NEXT
and RETURN QUERY
freely and repeatedly. The underlying principle is that PL/pgSQL builds the table locally and does not return until the function is finished:
Note: The current implementation of
RETURN NEXT
andRETURN QUERY
stores the entire result set before returning from the function, ...
You can raise an exception to abort the operation if you are unsatisfied with the results so far and the client won't see a thing. We also included an example in the manual demonstrating this, just above said quote.
Cross tabulation
As for what you are trying do achieve, consider the crosstab()
function from the tablefunc
extension. See: