1

In MySQL it's very easy to update a table over the result of an order by, such as the following:

SET @counter=1;
UPDATE task SET priority = (@counter:=@counter+1) ORDER BY createdAt ASC;

What would be the equivalent query on PostgreSQL?

1 Answer 1

3

You can use an UPDATE with a JOIN to a table of row numbers generated with the ROW_NUMBER() function (selecting row numbers based on the order of createdAt):

UPDATE task
SET priority = p.priority
FROM (SELECT createdAt, ROW_NUMBER() OVER (ORDER BY createdAt) AS priority
      FROM task) p 
WHERE p.createdAt = task.createdAt

Demo on dbfiddle

Sign up to request clarification or add additional context in comments.

Comments

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.