SQL ALTER TABLE Statement
The ALTER TABLE
statement in SQL allows you to modify the structure of an existing table in your database. This is a very important command for managing and adapting your database schema as your needs change.
ALTER TABLE: Definition and Usage
ALTER TABLE
enables you to make changes to your table's design after it's been created. You can add new columns, delete existing columns, or modify the properties of existing columns (like data types or constraints). Modifying a table's structure is a powerful capability, but make sure you understand the implications of your changes, especially when altering data types or removing columns, as data may be lost or require conversion.
Adding Columns
The ADD
clause adds a new column to the table. You specify the column name and its data type.
Syntax
ALTER TABLE table_name
ADD column_name data_type;
Example: Adding an Email Column
Syntax
ALTER TABLE Customers
ADD Email VARCHAR(255);
Output
(A new column named 'Email' of type VARCHAR(255) is added to the 'Customers' table. Existing rows will initially have NULL values in this new column.)
Deleting Columns
The DROP COLUMN
clause removes a column. This is a destructive action; the column and its data are permanently deleted.
Syntax
ALTER TABLE table_name
DROP COLUMN column_name;
Example: Deleting the Email Column
Syntax
ALTER TABLE Customers
DROP COLUMN Email;
Output
(The 'Email' column is deleted from the 'Customers' table. The data in that column is lost.)