Search code examples
sqlpostgresqljoinsql-update

Postgres RETURNING clause with join


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.


Solution

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