Every now and then I need a function that returns nothing.
As you perhaps know, even defining function as “RETURNS VOID" doesn't fully solve the problem:
$ BEGIN; CREATE function testit() RETURNS void as $$ BEGIN RETURN; END; $$ language plpgsql; CREATE FUNCTION $ SELECT testit(); testit -------- (1 row)
1 row?! Clearly there is something returned.
So, can it be done any better? Well, yes. Since (as we saw) the function returns at least one row, perhaps we can make it to return 0-row recordset? Like this:
$ CREATE function testit() RETURNS setof void as $$ BEGIN RETURN; END; $$ language plpgsql; CREATE FUNCTION $ SELECT testit(); testit -------- (0 rows)
When using older version of PostgreSQL, you might get error like:
$ select testit(); ERROR: set-valued function called in context that cannot accept a set CONTEXT: PL/pgSQL function "testit" while casting return value to function's return type
In such case, just change the query to:
$ select * from testit(); testit -------- (0 rows)
One last thing – if you're running it via psql, and you want to get rid of the “testit" header, line below, and “0 rows" summary, just run psql with “-t" option, or enter “\t" in psql session, to turn on “tuples-only" mode.