ALTER TABLE ADD COLUMN takes a long time

后端 未结 3 844
青春惊慌失措
青春惊慌失措 2020-12-02 05:14

I was just trying to add a column called \"location\" to a table (main_table) in a database. The command I run was

ALTER TABLE main_table ADD COLUMN location         


        
3条回答
  •  没有蜡笔的小新
    2020-12-02 05:39

    Alter table takes a long time with a big data like in your case, so avoid to use it in such situations, and use some code like this one:

    select main_table.*, 
      cast(null as varchar(256)) as null_location, -- any column you want accepts null
      cast('' as varchar(256)) as not_null_location, --any column doesn't accept null
      cast(0 as int) as not_null_int, -- int column doesn't accept null
    into new_table 
    from main_table;
    
    drop table main_table;
    rename table new_table TO main_table;
    

提交回复
热议问题