PostgreSQL stored procedure to return rows or empty set
You can do something along the following lines:

test=&gt; CREATE OR REPLACE FUNCTION temptabl(cnt integer)
RETURNS SETOF integer AS
$body$
BEGIN
    CREATE TEMPORARY TABLE tmp_container ON COMMIT DROP AS
    SELECT a
    FROM generate_series(1, cnt) t(a);

    IF (SELECT count(1) FROM tmp_container) &gt; 5
    THEN
        RETURN QUERY SELECT a FROM tmp_container;
    END IF;
END;
$body$
LANGUAGE plpgsql;


test=&gt; SELECT * FROM temptabl(4);
 temptabl 
----------
(0 rows)

test=&gt; SELECT * FROM temptabl(6);
 temptabl 
----------
        1
        2
        3
        4
        5
        6
(6 rows)


This way you have to perform your original query only once.  All other statements work on the temporary table.