MySQL ALTER Command
Overview
The ALTER TABLE statement is used to modify the structure of an existing table. You can add, delete, or modify columns, indexes, and constraints after a table has been created.
Common ALTER Operations
- Add Columns: Add new columns to tables
- Drop Columns: Remove columns from tables
- Modify Columns: Change column definitions
- Rename Columns: Change column names
- Add Constraints: Add PRIMARY KEY, FOREIGN KEY, etc.
- Drop Constraints: Remove constraints
- Change Options: Modify table options
ALTER TABLE Syntax
Basic Syntax
Adding Columns
Add Single Column
Add Multiple Columns
Add Column with Position
Add Column with Constraint
Dropping Columns
Drop Single Column
Drop Multiple Columns
Drop and Add Column
Modifying Columns
CHANGE vs MODIFY
Change Data Type
Change Default Value
Add AUTO_INCREMENT
Renaming Columns
Renaming Table
Altering Constraints
Adding Primary Key
Dropping Primary Key
Adding Foreign Key
Dropping Foreign Key
Adding UNIQUE Constraint
Dropping UNIQUE Constraint
Altering Indexes
Adding Indexes
Dropping Indexes
Altering Table Options
Change Engine
Change Character Set
Change Auto Increment
Add Table Comment
Complex ALTER Operations
Reorder Columns
Convert to Different Format
Performance Considerations
ALTER Table Performance
ALGORITHM Option
LOCK Option
Practical Examples
Migration: Add User Status
Migration: Add Soft Delete
Migration: Add Audit Columns
Migration: Normalize Data
Troubleshooting
Common Errors
Checking Table Structure
Summary
ALTER TABLE allows you to:
ALTER TABLE:
- Modify Structure: Add, drop, change columns
- Manage Constraints: Add and drop keys
- Change Options: Engine, character set, auto-increment
- Online DDL: Use ALGORITHM and LOCK options
Consider performance impact when modifying large tables and use appropriate ALGORITHM and LOCK options.
Previous: Transactions
Next: Indexes