T-SQL ALTER TABLE Examples
Here are various code examples for using
ALTER TABLE in Transact-SQL (T-SQL).
Add a Column
The following code adds a new column called
TaskDescription to the
Tasks table. This column has a data type of
varchar(255) and it's allowed to have null values.
Change the Size of a Column
This example increases the size of the
TaskDescription column to
Add a Unique Constraint
This example adds a new column called
TaskCode with a unique constraint.
Drop a Unique Constraint
Here, we drop the unique constraint that we created in the previous example (i.e. we remove it).
Change a Column's Data Type
This example changes the data type of the
TaskCode column to
DEFAULT constraint sets a default value for a column in the event that no value has been provided.
In this example, if a new row is added but no value has been provided for the
TaskDescription column, a value of
TBA will be inserted.
FOREIGN KEY Constraint
This example creates a relationship between two tables (the
Albums table and the
Artists) table). We do this by creating a foreign key constraint on the
Albums table. We specify that the
Albums.ArtistId column is a foreign key to the
Drop a Column
Here, we drop the