1

I've got this query that updates some rows and returns the updated rows in the RETURNING clause. However, even though I've specified ORDER BY mycolumn in the inner query, the rows returned by RETURNING aren't ordered.

UPDATE mytable SET status = 'A'
FROM
  (
    SELECT id FROM mytable
    WHERE status = 'B'
    ORDER BY mycolumn
    LIMIT 100
    FOR UPDATE
  ) sub
  JOIN jointable j ON j.id = sub.id
WHERE mytable.id = sub.id
RETURNING *

I tried putting an ORDER BY in the outer query, like after the JOIN or after the WHERE, but I get an error in both cases. How can I make it return the rows in the desired order?

(A similar question was answered in Update Returning Order by in postgresql but that doesn't include JOINs, only ORDER.)

1 Answer 1

3

Use CTE:

WITH updated as(
    UPDATE mytable SET status = 'A'
FROM
  (
    SELECT id FROM mytable
    WHERE status = 'B'
    ORDER BY mycolumn
    LIMIT 100
    FOR UPDATE
  ) sub
  JOIN jointable j ON j.id = sub.id
WHERE mytable.id = sub.id
RETURNING *
)
select *
from updated
ORDER BY mycolumn
Sign up to request clarification or add additional context in comments.

3 Comments

I get an error ORDER BY "mycolumn" is ambiguous. If I take out the last ORDER BY, there's no error. So the inner ORDER BY is fine, it's the outer one that gives the error. I suppose it's because both tables in the join have a mycolumn. How can I get the ordering to work then?
Instead of RETURNING *, write down the columns you need.
For example: RETURNING j.id, sub.mycolumn, remember that you have to use specific aliases

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.