ALTER TABLE Statement π§ΒΆ
Prerequisites: CREATE TABLE
Mentor's Note: Requirements change. You built a "Users" table, but now the client wants to store "Phone Numbers". You don't need to delete the table and start over; you just Renovate it! π‘
π The Scenario: The Home Renovation π ΒΆ
- Add Column: Building a new balcony.
- Drop Column: Removing an old fireplace.
- Modify Column: Expanding a small window into a large glass door.
π» 1. ADD Column (Expansion) βΒΆ
Add a new field to your table.
-- Syntax
ALTER TABLE table_name ADD column_name datatype;
-- Example: Add Email to Students
ALTER TABLE students ADD email VARCHAR(100);
π» 2. DROP Column (Cleanup) βοΈΒΆ
Remove a field you no longer need. Warning: Deletes all data in that column!
-- Syntax
ALTER TABLE table_name DROP COLUMN column_name;
-- Example: Remove Age (Calculate it from DOB instead)
ALTER TABLE students DROP COLUMN age;
π» 3. MODIFY / ALTER Column (Renovation) π οΈΒΆ
Change the data type or size of a column.
π‘ Important RulesΒΆ
- Not Null to Null: You can usually easily relax a rule.
- Null to Not Null: You can only do this if the column currently has NO null values.
- Reducing Size: You cannot shrink a
VARCHAR(100)toVARCHAR(10)if you already have a 50-character name stored.