Passing a ResultSet into a Postgresql Function

Ben Hamner picture Ben Hamner · Aug 14, 2013 · Viewed 7.1k times · Source

Is it possible to pass the results of a postgres query as an input into another function?

As a very contrived example, say I have one query like

SELECT id, name
FROM users
LIMIT 50

and I want to create a function my_function that takes the resultset of the first query and returns the minimum id. Is this possible in pl/pgsql?

SELECT my_function(SELECT id, name FROM Users LIMIT 50); --returns 50

Answer

Erwin Brandstetter picture Erwin Brandstetter · Oct 16, 2013

You could use a cursor, but that very impractical for computing a minimum.

I would use a temporary table for that purpose, and pass the table name for use in dynamic SQL:

CREATE OR REPLACE FUNCTION f_min_id(_tbl regclass, OUT min_id int) AS 
$func$
BEGIN

EXECUTE 'SELECT min(id) FROM ' || _tbl
INTO min_id;

END  
$func$ LANGUAGE plpgsql;

Call:

CREATE TEMP TABLE foo ON COMMIT DROP AS
SELECT id, name
FROM   users
LIMIT  50;

SELECT f_min_id('foo');

Major points

-> SQLfiddle demo