Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

When performing

RETURN QUERY ...

in a PL/pgSQL function, is it possible afterwards to directly access the number of rows accumulated into the pile of records, which are returned when the function ends?

Example:

RETURN QUERY SELECT * FROM tableA; -- 14 records
RETURN QUERY SELECT * FROM tableB; -- 8 records
RETURN QUERY SELECT * FROM tableC; -- 22 records

The number of accumulated records should now be 44.

share|improve this question
add comment

1 Answer

up vote 5 down vote accepted

Use

GET DIAGNOSTICS integer_var = ROW_COUNT;

More in the manual in the chapter Obtaining the Result Status.
Your example could look like this:

CREATE OR REPLACE FUNCTION f_test()
  RETURNS SETOF table_a AS
$func$
DECLARE
    i  int;
    ct int := 0;
BEGIN

RETURN QUERY SELECT * FROM table_a;    -- 14 records
GET DIAGNOSTICS i = ROW_COUNT;  ct := ct + i;

RETURN QUERY SELECT * FROM table_b;    -- 8 records
GET DIAGNOSTICS i = ROW_COUNT;  ct := ct + i;

RETURN QUERY SELECT * FROM table_c;    -- 22 records
GET DIAGNOSTICS i = ROW_COUNT;  ct := ct + i;

RAISE NOTICE 'Returned % rows', ct;    -- 44

END
$func$ LANGUAGE plpgsql
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.