SQL ALTER TABLE statement
Here is a clear, practical, and complete guide to the SQL ALTER TABLE statement, including examples for MySQL, PostgreSQL, SQL Server, and Oracle.
β
What ALTER TABLE Does
ALTER TABLE modifies the structure of an existing table.
You can:
-
Add columns
-
Modify columns
-
Drop columns
-
Rename columns
-
Add or drop constraints
-
Rename the table
πΉ Basic Syntax
π¦ 1. ADD COLUMN
Add multiple columns (MySQL/PostgreSQL):
π§ 2. DROP COLUMN
SQL Server requires:
(Same syntaxβbut SQL Server cannot drop columns involved in constraints unless removed first.)
πͺ 3. MODIFY / ALTER COLUMN
MySQL:
PostgreSQL:
SQL Server:
π¨ 4. RENAME COLUMN
PostgreSQL:
SQL Server:
MySQL:
π¦ 5. ADD CONSTRAINT
Primary key:
Unique:
Foreign key:
π§ 6. DROP CONSTRAINT
PostgreSQL:
SQL Server:
MySQL:
(In MySQL, UNIQUE constraints are indexes.)
π¨ 7. RENAME TABLE
MySQL / PostgreSQL:
SQL Server:
π₯ 8. SET DEFAULT / DROP DEFAULT
Add default:
Drop default:
(SQL syntax varies slightly across engines.)
β οΈ Important Notes & Pitfalls
β ALTER TABLE locks the table in many databases (be careful in production)
β Always back up before major schema changes
β Dropping columns removes all stored data in that column
β Changing column types can fail if existing data is incompatible
β Foreign key changes may require dropping/recreating constraints
π Best Practices
β Apply changes in small, safe migrations
β Avoid long ALTER operations on huge tables during peak hours
β Use CHECK, UNIQUE, and FOREIGN KEY constraints for data integrity
β Use meaningful constraint names (e.g., fk_orders_userid)
β Test ALTER statements on staging before production
