21

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.

1
  • The row in sub consists of one column, which is in mytable. As written, the question is overly simplified. Commented Dec 17, 2016 at 22:25

1 Answer 1

28

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
;    
Sign up to request clarification or add additional context in comments.

1 Comment

Could you please take a look at my question stackoverflow.com/questions/41387603/…? It's about the same SQL statement you've listed here, except I can't get it to follow the ORDER BY mycolumn in the outer RETURNING query. Thanks!

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.