I am just starting out on functions in PostgreSQL, and this is probably pretty basic, but how is this done?
I would like to be able to use the following in a function:
PERFORM id_exists();
IF FOUND THEN
-- Do something
END IF;
where the id_exists() function (to be used with SELECT and PERFORM) is:
CREATE OR REPLACE FUNCTION id_exists() RETURNS int AS $$
DECLARE
my_id int;
BEGIN
SELECT id INTO my_id
FROM tablename LIMIT 1;
RETURN my_id;
END;
$$ LANGUAGE plpgsql;
Currently, even when my_id does not exist in the table, FOUND is true, presumably because a row is still being returned (a null integer)? How can this be re-written so that an integer is returned if found, otherwise nothing at all is?
Your assumption is correct,
FOUNDis set toTRUEif the last statement returned a row, regardless of the value (may beNULLin your case). Details in the manual here.Rewrite to, for instance:
Or rewrite the return value of your function with
SETOFso it can return multiple rows – or no row! UseRETURN QUERYlike I demonstrate. You can use this function in your original setting.Or, even simpler with a language SQL function: