0

say, i have a table t with only 2 fields, like below

ID    VALUE
---------------------
0      100   
0      103   
0      101   
0      102  
...
...
...
0      110,000,000 

i need to update the id fields using their ordered sequence and change the table , like below:

ID    VALUE
---------------------
1      100   
2      101   
3      102   
4      103   
...
...
...
109999901       110,000,000 

How do i write the sql script in mysql to make this happen? Seems like in Oracle it's much easier.

2 Answers 2

1

One method is:

update t join
       (select t.*, row_number() over (order by value) as seqnum
        from t
       ) tt
       on t.value = tt.value
    set t.id = tt.seqnum;

However, a better method might use variables:

set @rn := 0;

update t
    set id = (@rn := @rn + 1)
    order by value;

For these, you would want an index on (value). You would have better performance by just creating a new table, though.

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

Comments

0

If you are using MySQL 8+, then I suggest actually not doing this update, but instead just use a select along with ROW_NUMBER:

SELECT ROW_NUMBER() OVER (ORDER BY ID), VALUE
FROM yourTable
ORDER BY ID;

You could also put the above select into a view and use that if you have a frequent need to view your data in this way. The reason for not wanting to do an update is that should you insert new ID values which occur in the middle of your current sequence, you might be forced to run the update again. This could get to be a burden after a while.

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.