I have a PostgreSQL stored procedure that contains the following code:
IF something = TRUE THEN
SELECT id INTO some_id FROM some_table WHERE some conditions LIMIT 1;
RETURN QUERY SELECT * FROM some_table WHERE some conditions LIMIT 1;
ELSE
SELECT id INTO some_id FROM some_table WHERE some OTHER conditions LIMIT 1;
RETURN QUERY SELECT * FROM some_table WHERE some OTHER conditions LIMIT 1;
END IF;
DELETE FROM some_table where id = some_id;
Is there a way to simplify the above code? I guess there is nothing we can do
about the repeated code in the IF and in the ELSE, but is there a way to avoid
having 2 SELECT's every time? Is it possible to insert something in some_id while
RETURN QUERY?
RETURN QUERY EXECUTE ...in newer versions and do it with a dynamic SQL string created withformatand string concatenation.DELETEstatement never gets executed, because both of yourIFbranches has aRETURNstatement.RETURN QUERYdoes not exit from the function (unlikeRETURN).EXECUTEhere. Nothing dynamic, just two cases.QUERY--RETURN QUERYreally does not exit.