The SQL ALTER TABLE statement is used to modify an existing table structure. It allows you to add, modify, or drop columns, as well as add or drop constraints like primary keys, foreign keys, and indexes. Here are some common uses of the ALTER TABLE statement:
Adding a Column:
ALTER TABLE table_name
ADD column_name datatype;
Modifying a Column:
ALTER TABLE table_name
MODIFY column_name datatype;
Dropping a Column:
ALTER TABLE table_name DROP COLUMN column_name;
Adding a Primary Key Constraint:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column_name);
Dropping a Primary Key Constraint:
ALTER TABLE table_name DROP CONSTRAINT constraint_name;
Adding a Foreign Key Constraint:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name FOREIGN KEY (column_name)
REFERENCES other_table (other_column);
Dropping a Foreign Key Constraint:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
Adding an Index:
ALTER TABLE table_name
ADD INDEX index_name (column_name);
Dropping an Index:
ALTER TABLE table_name
DROP INDEX index_name;