In the following SQL, how could I make the RETURNING
clause join to something else and return the joined row(s)? Here it only returns the row from mytable
that was updated, but I'd like it to return that row joined to something in another table.
UPDATE mytable
SET status = 'A'
FROM (
SELECT myid
FROM mytable
WHERE status = 'B'
ORDER BY mycolumn
LIMIT 100
FOR UPDATE
) sub
WHERE mytable.myid = sub.myid
RETURNING *;
I could do another query from my client application, but I'd like to know if there's a way to do it from within Postgres within having to make a separate roundtrip to the DB.
Return Value: The join() method returns a string concatenated with the elements of iterable.
A common shorthand is RETURNING * , which selects all columns of the target table in order. In an INSERT , the data available to RETURNING is the row as it was inserted. This is not so useful in trivial inserts, since it would just repeat the data provided by the client.
merge join: Each relation is sorted on the join attributes before the join starts. Then the two relations are scanned in parallel, and matching rows are combined to form join rows. This kind of join is attractive because each relation has to be scanned only once.
Description The RETURNING clause allows you to retrieve values of columns (and expressions based on columns) that were modified by an insert, delete or update. Without RETURNING you would have to run a SELECT statement after the DML statement is completed to obtain the values of the changed columns.
Anything in the FROM
clause is fair game for RETURNING
:
UPDATE mytable
SET status = 'A'
FROM
(
SELECT
myid
FROM mytable
WHERE status = 'B'
ORDER BY mycolumn
LIMIT 100
FOR UPDATE
) sub
JOIN jointable j ON j.id = sub.myid
WHERE mytable.myid = sub.myid
RETURNING mytable.mycolumn, j.othercolumn
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With