HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlModerate

How to access the number of rows accumulated by RETURNs in PL/pgSQL

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
rowsnumbertheaccumulatedreturnshowpgsqlaccess

Problem

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.

Solution

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

Code Snippets

GET DIAGNOSTICS integer_var = ROW_COUNT;
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$;

Context

StackExchange Database Administrators Q#37433, answer score: 11

Revisions (0)

No revisions yet.