0

How can I make a postgres SQL function that uses the value from a deleted row in the next query? It's straightforward to do in PLPGSQL by using a variable, but since there's no variables in SQL functions, how can I do it?

delete from mytable where key1 = '1' and key2 = '2' returning otherkey;
update mytable set otherkey = OTHERKEY where key1 = '1' and otherkey = '2';
-- "OTHERKEY" is the value returned by the first query

Is there a way to do it using a subquery?

1 Answer 1

2

Postgres supports data modification statements in CTEs -- with the returning clause.

So, you can do pretty much exactly what you want:

with d as (
      delete from mytable
          where key1 = '1' and key2 = '2'
          returning otherkey
     )
update mytable
    set otherkey = d.OTHERKEY
    from d
    where key1 = '1' and otherkey = '2';
Sign up to request clarification or add additional context in comments.

5 Comments

Since a CTE can return multiple rows how does the update statement know that d.OTHERKEY is just a single value rather than multiple values? Couldn't it be multiple values? If I were using it in a WHERE wouldn't I have to say where column in (d.OTHERKEY) rather than where column = d.OTHERKEY?
@user779159 . . . This addresses the question that you have asked, which is how to combine the delete and update in Postgres. Your question is specifically in the singular "a deleted row". Your question does not address the connection between the tables. However, if there is a primary key, then you would include that in the where condition.
Regarding your edit would it really not update any values? The where clauses in both queries are different.
If the returning returns one row then postgres lets you use it after an equals sign to check for equality. But if it returns more than one row then the query will give an error at runtime?
@user779159 . . . No. I think it will update all matching rows with an arbitrary value of OTHERKEY from one of the rows in d.

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.