0

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?

5
  • You can use RETURN QUERY EXECUTE ... in newer versions and do it with a dynamic SQL string created with format and string concatenation. Commented Sep 25, 2014 at 14:12
  • Your DELETE statement never gets executed, because both of your IF branches has a RETURN statement. Commented Sep 25, 2014 at 17:43
  • @pozs: No. RETURN QUERY does not exit from the function (unlike RETURN). Commented Sep 25, 2014 at 18:11
  • @CraigRinger: No need for EXECUTE here. Nothing dynamic, just two cases. Commented Sep 25, 2014 at 18:14
  • @ErwinBrandstetter of course, my bad. That's just the silly syntax highlight, which does not emphasise QUERY -- RETURN QUERY really does not exit. Commented Sep 25, 2014 at 18:21

1 Answer 1

3

If the function does only what you posted then it is not necessary:

delete from some_table
where 
    something and (some conditions)
    or
    something is not true and (some other conditions)
returning *
Sign up to request clarification or add additional context in comments.

1 Comment

Missed the something IS NULL case. If something can be NULL, then use or something IS NOT TRUE for the 2nd expression to do the same as the IF statement above (or OP needs to re-examine what to do for TRUE / FALSE / NULL).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.