I want to write a SQL function which returns true
if a certain INSERT
inserted a row and false
if no row was inserted. In this use case, we know that at most one row can be inserted.
I came up with the following solution:
create function test() returns boolean as
$$
with
dummy as
(
insert into ...
select ...
from ...
where ... -- this will limit to at most one row
returning true
)
select exists(select true from dummy);
$$
language sql volatile;
This seems to work fine, but it is rather clumsy and verbose, in my opinion. Is there something better possible?
I first wanted to write the following:
create function test() returns boolean as
$$
insert into ...
select ...
from ...
where ...
returning true;
$$
language sql volatile;
The problem now is that not false
but null
is returned when no row was inserted.
Best Answer
One way with little noise in the code:
The function, being declared as
returns boolean
(and notreturns setof boolean
) returns only the first row. If noINSERT
happens, the first (and only) row deliversfalse
.Or, a shorter version of your first variant:
See:
Related (with alternatives):
Quoting the manual to clarify the behavior of SQL functions:
Bold emphasis mine.
Note: the above is a single query. And we don't need
ORDER BY
, since a plainUNION ALL
without more operations in the outer query level simply appends the resulting row to the set in last position.