Alter Table - SQL

The SQL ALTER TABLE statement is a powerful command used to modify the structure of an existing table within a relational database management system (RDBMS). This statement enables database administrators and developers to make a wide range of changes to a table, including adding, modifying, or dropping columns, constraints, indexes, and more.

The syntax for the ALTER TABLE statement in SQL varies slightly depending on the specific alteration being performed. However, the general structure is as follows:

Syntax
ALTER TABLE table_name
    alteration_type [alteration_specification];
Where
  • table_name: Specifies the name of the table to be altered.
  • alteration_type: Indicates the type of alteration to be performed (e.g., ADD, MODIFY, DROP).
  • alteration_specification: Provides additional details specific to the type of alteration being made.

Adding Columns

Syntax
ALTER TABLE table_name
    ADD column_name data_type [column_constraint];
Example
ALTER TABLE employees
    ADD email VARCHAR(255) NOT NULL;

Modifying Columns

Syntax
ALTER TABLE table_name
    MODIFY column_name new_data_type [column_constraint];  
Example
ALTER TABLE employees
    MODIFY email VARCHAR(320) NOT NULL; 

Dropping Columns

Syntax
ALTER TABLE table_name
    DROP COLUMN column_name;
Example
ALTER TABLE employees
    DROP COLUMN email;

Adding Constraints

Syntax
ALTER TABLE table_name
    ADD CONSTRAINT constraint_name constraint_type (column_list);
Example
ALTER TABLE orders
    ADD CONSTRAINT fk_customer_id
    FOREIGN KEY (customer_id)
    REFERENCES customers(id);

Dropping Constraints

Syntax
ALTER TABLE table_name
    DROP CONSTRAINT constraint_name;
Example
ALTER TABLE orders
    DROP CONSTRAINT fk_customer_id;

Conclusion

In summary, the SQL ALTER TABLE statement provides a versatile mechanism for modifying the structure of database tables, allowing for flexibility in adapting to evolving data requirements. By understanding the syntax, common alterations, and associated considerations, database administrators and developers can effectively manage table structures within their relational databases.