0

In a plpgsql function I'm doing returns table with a few columns to return a table with a few rows. But now I want to also return an individual scalar value along with it. So one individual scalar value, plus several rows. How can I do this?

An example is

select count(*) from exampletable into individidual_scalar_value;
select a, b, c from anothertable into several_rows limit 10;
4
  • A function cannot return both a table and a scalar. You have to re-think what you want to accomplish. I might suggest two different functions. Commented May 19, 2019 at 11:23
  • @GordonLinoff Could it return a scalar and json representation of table instead? I tried wrapping select statement in something like to_json but that didn't work but I think there is a way? Commented May 19, 2019 at 11:41
  • . . It could return two values as a composite type or a row in a table. This seems like an odd requirement. You should explain more about what you are really trying to do. Commented May 19, 2019 at 12:21
  • The query already exists and is returning several rows (e.g. from a plpgsql returns table or returns some_custom_type). I now want to return an additional scalar value (such as the count of a table). The normal way to do it would be to just add a brand new function to return the scalar, and keep the existing function unchanged. But since these two values (the rows and the new scalar) will always be used together, I'd like to see what options there are to return them from the same function. Commented May 19, 2019 at 12:46

1 Answer 1

1

You could use a subquery for the count on the first table:

select a, b, c, (select count(*) from exampletable)
from anothertable
into several_rows
limit 10;

But note that in general, using LIMIT without ORDER BY is fairly meaningless, because you are not telling Postgres which 10 records you want to actually select. So, add a sensible ORDER BY clause to the above query for best results.

Sign up to request clarification or add additional context in comments.

4 Comments

Does the count(*) get calculated for each row? I would assume it just gets calculated once and copied to each rows but does the explain output or anything else "prove" this?
@user779159 Yes, the count subquery is not correlated with the outer query, and therefore should be computed once, and then cached. Running explain should reveal this.
When anothertable doesn't return any rows then the scalar value doesn't get returned. Do you know how I could do this another way? Maybe with OUT parameters?
This seems like an odd requirement. Why not just let the caller handle the case where no rows get returned?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.