16

I have the following query that works fine

SELECT RecordID, ROW_NUMBER() OVER (ORDER BY (Value1) DESC) AS Rank
FROM Table1

Also, I have another table(table2) that contains (among others) the fields RecordID and Rank. I would like to update RecordID and Rank in table2 based on result of query above. Is that possible?

2

2 Answers 2

30

Yes, you can have multiple tables in an update in Postgres:

update table2
    set rank = t1.rank
    from (SELECT RecordID, ROW_NUMBER() OVER (ORDER BY (Value1) DESC) AS Rank
          FROM Table1
         ) t1
    where table2.RecordId = t1.RecordId;
Sign up to request clarification or add additional context in comments.

2 Comments

I believe it needs to be from (select ...) as t1, without the "as" I get an error
@MattGreer . . . Postgres definitely does not require as to declare table aliases. Perhaps you should ask a question for the database you are actually using.
8

What worked for me (in mysql) was :

update table2, (SELECT RecordID, ROW_NUMBER() OVER (ORDER BY (Value1) DESC) AS Rank 
    FROM Table1) tempTable 
set table2.Rank = tempTable.Rank 
where table2.RecordId = tempTable.RecordId;

3 Comments

Tested in mysql, can be helpful for people searching a solution not necessarily for Postgres.
But the question is tagged with postgresql
I found this question by searching for a similar issue not specifically for postgresql, others may also find it useful.

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.