sql-server
  1. sql-server-alter-table

ALTER Table - ( SQL Server Database )

The ALTER TABLE statement is used to add, modify, or drop columns in an existing table in SQL Server. In this page, we will discuss how to use the ALTER TABLE statement in SQL Server.

Syntax

Here's the basic syntax for the ALTER TABLE statement:

ALTER TABLE table_name
ADD column_name datatype;

ALTER TABLE table_name
ALTER COLUMN column_name datatype;

ALTER TABLE table_name
DROP COLUMN column_name;

The ADD keyword is used to add a new column to an existing table. The ALTER COLUMN keyword is used to modify the data type of an existing column. The DROP COLUMN keyword is used to remove a column from an existing table.

Example

Here's an example of how to use the ALTER TABLE statement in SQL Server:

ALTER TABLE Customers
ADD EmailAddress nvarchar(100);

ALTER TABLE Customers
ALTER COLUMN EmailAddress nvarchar(255);

ALTER TABLE Customers
DROP COLUMN EmailAddress;

Output

When you execute the ALTER TABLE statements above, the following changes are made to the Customers table:

  • The EmailAddress column is added with a data type of nvarchar(100).
  • The data type of the EmailAddress column is modified to nvarchar(255).
  • The EmailAddress column is dropped from the table.

Explanation

The ALTER TABLE statement is used to modify the structure of an existing table, including adding, modifying, or dropping columns. When adding a new column, you specify the column name and data type to add the column with ADD syntax. When modifying a column, you use ALTER COLUMN syntax and specify the new data type for the column. When dropping a column, you use the DROP COLUMN keyword followed by the name of the column you wish to delete.

Use

You can use the ALTER TABLE statement in SQL Server to make changes to an existing table in your database. It's a useful statement when you need to add, modify, or remove columns from an existing table.

Important Points

  • When using the ALTER TABLE statement, you need to specify the name of the table you want to modify.
  • The ADD keyword is used to add a new column to an existing table- The ALTER COLUMN keyword is used to modify the data type of an existing column.
  • The DROP COLUMN keyword is used to remove a column from an existing table.

Summary

In this page, we discussed how to use the ALTER TABLE statement in SQL Server. We covered the syntax, example, output, explanation, use, and important points of the statement. With the ALTER TABLE statement, you can add, modify, or remove columns from an existing table in your SQL Server database.

Published on: