5

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.

Chau
  • 289
  • 1
  • 5
  • 9

1 Answers1

11

Use:

GET DIAGNOSTICS integer_var = ROW_COUNT;

Read the manual chapter "Obtaining the Result Status".
Your example could look like this:

CREATE OR REPLACE FUNCTION f_test()
  RETURNS SETOF table_a
  LANGUAGE plpgsql 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$;

fiddle

Erwin Brandstetter
  • 185,527
  • 28
  • 463
  • 633