MySQL ALTER TABLE
MySQL ALTER TABLE: Updating Existing Table Schemas
The MySQL ALTER TABLE statement modifies the structure of an existing table without losing stored rows. You use ALTER TABLE in migrations to add new columns, adjust column widths, rename fields, or attach indexes and foreign keys.
Common ALTER TABLE Operations
- Add a Column:
ADD COLUMN phone VARCHAR(20) NULL AFTER email - Change Column Type:
MODIFY COLUMN status VARCHAR(32) NOT NULL DEFAULT 'pending' - Rename a Column (MySQL 8.0+):
RENAME COLUMN full_name TO display_name - Drop a Column:
DROP COLUMN legacy_code - Add an Index:
ADD INDEX idx_demo_orders_status (status)
Practical SQL Example
This migration updates demo_customers by adding a phone column, widening city, and adding a lookup index in one combined ALTER TABLE pass:
ALTER TABLE demo_customers
ADD COLUMN phone VARCHAR(20) NULL AFTER email,
MODIFY COLUMN city VARCHAR(80) NOT NULL DEFAULT 'Unknown',
ADD INDEX idx_demo_customers_city (city);
-- Inspect the updated schema
DESCRIBE demo_customers;
Common Mistakes and Best Practices
- Combine Multiple Changes Into One
ALTER TABLE: CombiningADD COLUMNandADD INDEXin a singleALTER TABLEstatement avoids rebuilding the table multiple times on large datasets. - Never Lose Constraints Inside
MODIFY COLUMN: When runningMODIFY COLUMN, you must re-stateNOT NULLandDEFAULTvalues! RunningMODIFY COLUMN price DECIMAL(12, 2)withoutNOT NULLsilently flips the column back to nullable. - Test Online DDL Lock Behavior: Adding a nullable column at the end of a table uses
ALGORITHM=INSTANTin MySQL 8 without copying rows, whereas changing a column data type copies the table and can block writes.
Frequently Asked Questions
What is the difference between MODIFY COLUMN and CHANGE COLUMN?
MODIFY COLUMN changes a column's type or constraints without renaming it, while CHANGE COLUMN old_name new_name ... requires repeating the name even if unchanged (use RENAME COLUMN in MySQL 8 for simple renames).
Does ALTER TABLE lock the table in MySQL 8?
Instant and in-place algorithms (ADD COLUMN, ADD INDEX) allow concurrent reads and writes on InnoDB, though metadata locks wait briefly at start and finish.
How do I remove a default value with ALTER TABLE?
Run ALTER TABLE demo_customers ALTER COLUMN city DROP DEFAULT;.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.