SQL ALTER TABLE (Add, Drop, Modify)

Article Summary

ALTER TABLE lets you change an existing table’s structure β€” add, drop, or modify columns and constraints without losing data. πŸ”Ή Basic Syntax πŸ”Ή Examples πŸ”Ή Notes 🧠 Quick Recap Operation Syntax Example Add column ALTER TABLE table ADD column datatype; Drop column ALTER TABLE table DROP COLUMN column; Modify col ALTER TABLE table MODIFY […]

ALTER TABLE lets you change an existing table’s structure β€” add, drop, or modify columns and constraints without losing data.

πŸ”Ή Basic Syntax

-- Add a new column
ALTER TABLE table_name
ADD column_name datatype [constraints];

-- Drop a column
ALTER TABLE table_name
DROP COLUMN column_name;

-- Modify a column (syntax varies by DBMS)
ALTER TABLE table_name
MODIFY column_name new_datatype [constraints]; -- MySQL, Oracle

ALTER TABLE table_name
ALTER COLUMN column_name TYPE new_datatype; -- PostgreSQL, SQL Server

πŸ”Ή Examples

-- Add a column 'email' to 'employees'
ALTER TABLE employees
ADD email VARCHAR(100);

-- Drop 'salary' column from 'employees'
ALTER TABLE employees
DROP COLUMN salary;

-- Modify 'email' column to be NOT NULL (MySQL)
ALTER TABLE employees
MODIFY email VARCHAR(100) NOT NULL;

πŸ”Ή Notes

  • Syntax for modifying columns varies by DBMS β€” always check your DBMS docs.
  • Some DBMS don’t allow dropping columns easily (e.g., older versions of Oracle).
  • Use ALTER TABLE carefully, as structure changes affect existing data.

🧠 Quick Recap

OperationSyntax Example
Add columnALTER TABLE table ADD column datatype;
Drop columnALTER TABLE table DROP COLUMN column;
Modify colALTER TABLE table MODIFY column datatype; (MySQL, Oracle)

πŸ’‘ ALTER TABLE is powerful β€” use it to adapt your table as requirements change.

Was this helpful?