MySQL ALTER 命令

用 ALTER TABLE 改表结构:加列、改类型、加索引。

Beginner
Key PointsALTER 会锁表(8.0 的 INSTANT / INPLACE 可大幅减负),大表改结构要选低峰期。

常用操作

SQL
ALTER TABLE users ADD COLUMN phone VARCHAR(20) AFTER email;
ALTER TABLE users MODIFY COLUMN age SMALLINT UNSIGNED DEFAULT 0;
ALTER TABLE users DROP COLUMN phone;
ALTER TABLE users ADD INDEX idx_age (age);
ALTER TABLE users CHANGE username uname VARCHAR(60);
Output
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

8.0 的 INSTANT

SQL
-- 仅加列且允许 NULL / 默认值,8.0 可秒级完成(INSTANT 算法)
ALTER TABLE users ADD COLUMN remark VARCHAR(255), ALGORITHM=INSTANT;
On old versions ALTER locks and copies the whole table, killing production. For big tables prefer ALGORITHM=INSTANT (add column only) or pt-online-schema-change / gh-ost.

Friends & Partners