SQL ALTER TABLE
Statement
ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
SQL ALTER TABLE Syntax
To add a column in a table, use the following syntax:
To delete a column in a table, use the following syntax (note that some database systems do not allow deleting columns in this way):
To change the data type of a column in a table, use the following syntax:
SQL Server / MS Access:
MySQL / Oracle:
Oracle versions after 10G:
ALTER TABLE table_name
MODIFY column_name datatype;
SQL ALTER TABLE Example
Consider the "Persons" table:
P_Id | LastName | FirstName | Address | City |
---|---|---|---|---|
1 | Hansen | Ola | Timoteivn 10 | Sandnes |
2 | Svendson | Tove | Borgvn 23 | Sandnes |
3 | Pettersen | Kari | Storgt 20 | Stavanger |
Now, we want to add a column named "DateOfBirth" to the "Persons" table.
We use the following SQL statement:
Note that the new column "DateOfBirth" is of type date, which can store dates. The data type specifies the type of data that can be stored in a column. For information on available data types in MS Access, MySQL, and SQL Server, visit our complete Data Types Reference.
Now, the "Persons" table will look like this:
P_Id | LastName | FirstName | Address | City | DateOfBirth |
---|---|---|---|---|---|
1 | Hansen | Ola | Timoteivn 10 | Sandnes | |
2 | Svendson | Tove | Borgvn 23 | Sandnes | |
3 | Pettersen | Kari | Storgt 20 | Stavanger |
Changing Data Type Example
Now, we want to change the data type of the "DateOfBirth" column in the "Persons" table.
We use the following SQL statement:
Note that the "DateOfBirth" column is now of type year, which can store years in 2-digit or 4-digit format.
DROP COLUMN Example
Next, we want to delete the "DateOfBirth" column from the "Persons" table.
We use the following SQL statement:
Now, the "Persons" table will look like this:
P_Id | LastName | FirstName | Address | City |
---|---|---|---|---|
1 | Hansen | Ola | Timoteivn 10 | Sandnes |
2 | Svendson | Tove | Borgvn 23 | Sandnes |
3 | Pettersen | Kari | Storgt 20 | Stavanger |