29
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQL の ALTER TABLE ... SET DEFAULT は速い

Posted at

ALTER TABLE ... SET DEFAULT はデータを変更しないので速いです。

適当に大量の行を持つテーブルを作ります。

create table t (id int not null primary key auto_increment);
insert into t () values ();
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;
insert into t select null from t;

select count(*) from t;
/* 1048576 */

列追加はテーブル作りなおしなのでとても遅いです。

$ time mysql test -e 'alter table t add val int not null'

real    0m5.291s
user    0m0.002s
sys     0m0.002s

NULL 制約の付け外しも列の変更なのでとても遅いです。

$ time mysql test -e 'alter table t change val val int null'

real    0m4.871s
user    0m0.002s
sys     0m0.001s

$ time mysql test -e 'alter table t change val val int not null'

real    0m4.578s
user    0m0.003s
sys     0m0.001s

デフォルトの変更は ALTER ... SET DEFAULT を使えば高速です。

$ time mysql test -e 'alter table t alter val set default 2'

real    0m0.018s
user    0m0.002s
sys     0m0.000s

$ time mysql test -e 'alter table t alter val drop default'

real    0m0.017s
user    0m0.003s
sys     0m0.000s

例えばこんな時・・・

  • あるテーブルに列を追加する
  • 追加する列のデフォルト値は 1
  • ただし既存の行には全部 2 を設定する

この変更は・・・

alter table t add val int not null default 1;
update t set val = 2;

とするよりも・・・

alter table t add val int not null default 2;
alter table t alter val set default 1;

としたほうが早い。

29
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?