PostgreSQL – How to Access Number of Rows Accumulated by RETURNs in PL/pgSQL

functionsplpgsqlpostgresql

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.

Best Answer

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