Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alter a column length

Tags:

sql-server

I need to alter the length of a column column_length in say more than 500 tables and the tables might have no of records ranging from 10 records to 3 or 4 million records.

  1. The column may just be a normal column
CREATE TABLE test(column_length varchar(10))
  1. The column might contain non-clustered index on it.
CREATE TABLE test(column_length varchar(10))
CREATE UNIQUE NONCLUSTERED INDEX column_length_ind ON test (column_length)
  1. The column might contain PRIMARY KEY clustered index on it
CREATE TABLE test(column_length varchar(10))
ALTER TABLE test ADD PRIMARY KEY CLUSTERED INDEX ON column_length
  1. The column might be a composite primary key

  2. The column might have a foreign key reference

In short the column column_length might be anything.

All I need is to create scripts to alter the length of the column_length from varchar(10) to varchar(50). Should I drop the indexes before altering and then recreate them? What about the primary key and foreign key?

Through my research and testing I figured out that I can just alter the column's length without dropping the primary key or any indexes but have to drop and recreate the foreign key alone.

Is this assumption right?

like image 362
user21968 Avatar asked Feb 24 '26 17:02

user21968


1 Answers

Yes you should be able to just modify the columns. From my experience it is faster to leave the index and primary key in place.

like image 183
J.J. Avatar answered Feb 26 '26 08:02

J.J.



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!