Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a column with ROW_NUMBER() in SQL

I have added a new column to the table. Now i want to update this column with values from the function row_number().And i want to do it because i want to remove duplicate entries. The below mentioned code is not giving the desired output

UPDATE tab1
SET rownumber = (SELECT ROW_NUMBER() OVER(ORDER BY name ASC) 
             FROM tab1 AS a WHERE a.name = b.name)
FROM tab1 b

Problem is that when a new column is added in a table its values are null. Insert into adds new rows in the table but does not replace nulls. How to update null values with row numbers generated by function ROW_NUMBER().

The below mentioned table is what i have

name score

Bank of America 10

Commerce Bank 20

Wells Fargo Bank 135

Bank Midwest 45

Bank of America 10

Commerce Bank 20

now I want the output as after removing the duplicates

name score

Bank of America 10

Commerce Bank 20

Wells Fargo Bank 135

Bank Midwest 45

I was trying to add a new column with unique values to get the desired result.

like image 263
sam Avatar asked Nov 20 '25 06:11

sam


1 Answers

Try this:

UPDATE T
SET T.rownumber = TT.ROW_ID
FROM tab1 AS T
INNER JOIN (SELECT ROW_NUMBER() OVER (ORDER BY name) AS ROW_ID
                  ,name
            FROM Tab1) AS TT
    ON T.name = TT.name
like image 77
dario Avatar answered Nov 23 '25 09:11

dario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!