0

We have a table with more than 10million rows.

We are altering its column type like this:

ALTER TABLE MY_TABLE ALTER COLUMN MY_COLUMN VARCHAR(3)

What would be the fastest way to do this? Alter column needs to touch EVERY row right? Is there a way to make this faster?

According to questions and answers here, I'm thinking about, create a new table and migrate data, or create a new column with VARCHAR(3) and migrate only the data inside this column and drop the old column.

Obs. It's taking more than 3hrs.

  • 1
    What is the existing datatype? – Martin Smith May 18 '17 at 15:13
2

Referencing Aaron Bertrand's answer to a similar question, he says:

Depending on what change you are making, sometimes it can be easier to take a maintenance window. During that window (where nobody should be able to change the data in the table) you can:

1). drop any indexes/constraints pointing to the old column, and disable triggers

2). add a new nullable column with the new data type (even if it is meant to be NOT NULL)

3). update the new column setting it equal to the old column's value (and you can do this in chunks of individual transactions (say, affecting 10000 rows at a time using UPDATE TOP (10000) ... SET newcol = oldcol WHERE newcol IS NULL) and with CHECKPOINT to avoid overrunning your log)

4). once the updates are all done, drop the old column

5). rename the new column (and add a NOT NULL constraint if appropriate)

6). rebuild indexes and update statistics

The key here is that it allows you to perform the update incrementally in step 3, which you can't do in a single ALTER TABLE command.

This assumes the column is not playing a major role in data integrity - if it is involved in a bunch of foreign key relationships, there are more steps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.