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 varchar(500).

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 char(6).

Add a DEFAULT Constraint

A 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.

Add a 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 Artists.ArtistId column.

Drop a Column

Here, we drop the TaskCode Column.