Search code examples
sqlpostgresqlstored-proceduresplpgsqlsql-delete

Simplify PostgreSQL function


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?


Solution

  • 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 *