Return updated row attributes on UPDATE
Asked Answered
R

2

22

My query is as follow:

UPDATE t1 SET t1.foreign_key = (SELECT id FROM t2 WHERE t2.col = %s ) 
WHERE t1.col = %s

How do I return some attributes of the updated row in the table in the same query?

Rockey answered 15/8, 2016 at 3:9 Comment(0)
F
30

Use the RETURNING clause.

The optional RETURNING clause causes UPDATE to compute and return value(s) based on each row actually updated. Any expression using the table's columns, and/or columns of other tables mentioned in FROM, can be computed. The new (post-update) values of the table's columns are used.

Typically, it's smarter to use a join instead of a correlated subquery:

UPDATE t1
SET    foreign_key = t2.id
FROM   t2
WHERE  t2.col = %s
AND    t1.col = %s
RETURNING t1.*;   -- or only selected columns

With your original query, if the subquery finds no row in t2, t1 is updated anyway and t1.col is set to null. Typically, you'd rather not update the row in this case, which is what my query does instead.

BTW, target columns in the SET clause cannot be table-qualified (only one table is updated anyway). The manual once more:

Do not include the table's name in the specification of a target column — for example, UPDATE table_name SET table_name.col = 1 is invalid.

Fatimahfatimid answered 15/8, 2016 at 3:28 Comment(0)
L
11

You can use the RETURNING clause:

UPDATE t1
    SET t1.foreign_key = (SELECT id FROM t2 WHERE t2.col = %s ) 
    WHERE t1.col = %s
    RETURNING *;

The documentation is part of the UPDATE statement.

Leucocytosis answered 15/8, 2016 at 3:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.