Skip to content

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.

-- Expand name from 50 to 100 chars
ALTER TABLE students MODIFY first_name VARCHAR(100);
ALTER TABLE students ALTER COLUMN first_name VARCHAR(100);
ALTER TABLE students ALTER COLUMN first_name TYPE VARCHAR(100);

πŸ’‘ Important RulesΒΆ

  1. Not Null to Null: You can usually easily relax a rule.
  2. Null to Not Null: You can only do this if the column currently has NO null values.
  3. Reducing Size: You cannot shrink a VARCHAR(100) to VARCHAR(10) if you already have a 50-character name stored.

πŸ“ˆ Learning PathΒΆ