SQL ALTER TABLE: Modifying Columns
The ALTER TABLE
statement in SQL allows you to make changes to an existing table's structure. This includes adding, deleting, or modifying columns.
ALTER COLUMN: Changing Column Data Types
ALTER COLUMN Syntax
Use ALTER COLUMN
to change a column's data type. Be cautious, as this can affect existing data; make sure your data is compatible with the new data type.
Syntax
ALTER TABLE table_name
ALTER COLUMN column_name new_data_type;
Example: Changing BirthDate Data Type
This changes the 'BirthDate' column in the 'Employees' table to a 'year' data type. (The specific data types available depend on your database system.)
Syntax
ALTER TABLE Employees
ALTER COLUMN BirthDate year;
Output
The data type of the 'BirthDate' column in the 'Employees' table is changed to 'year'. Existing data must be compatible with this change.
DROP COLUMN: Deleting Columns
DROP COLUMN Syntax
Use DROP COLUMN
to remove a column from a table. This is a destructive operation; the column and all its data will be permanently removed.
Syntax
ALTER TABLE table_name
DROP COLUMN column_name;
Example: Deleting ContactName Column
This example removes the 'ContactName' column from the 'Customers' table.
Syntax
ALTER TABLE Customers
DROP COLUMN ContactName;
Output
The 'ContactName' column is removed from the 'Customers' table, along with all its data.