SQL ALTER TABLE statement
ALTER TABLE statement
ALTER TABLE statement is used in an existing table to add, delete, or modify columns.
SQL ALTER TABLE Syntax
To add a column in a table, use the following syntax:
ADD column_name datatype
To delete columns in a table, use the following syntax (Note that some database systems do not allow this to delete a column in a database table mode):
DROP COLUMN column_name
To change the data type of the table columns, use the following syntax:
SQL Server / MS Access:
ALTER COLUMN column_name datatype
My SQL / Oracle:
MODIFY COLUMN column_name datatype
SQL ALTER TABLE examples
See "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 called "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
ADD DateOfBirth date
Note that the new column "DateOfBirth" type is date, the date can be stored. Type specifies the type of data can be stored in a column of data. For MS Access, MySQL and SQL Server data types available, please access our complete Data Types Reference Manual .
Now, "Persons" table would be as follows:
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 |
Change the data type instances
Now, we want to change the "Persons" data type table "DateOfBirth" column.
We use the following SQL statement:
ALTER COLUMN DateOfBirth year
Please note that now "DateOfBirth" type column is year, can hold two or four year format.
Examples of DROP COLUMN
Next, we want to remove the "Person" table "DateOfBirth" column.
We use the following SQL statement:
DROP COLUMN DateOfBirth
Now, "Persons" table would be as follows:
P_Id | LastName | FirstName | Address | City |
---|---|---|---|---|
1 | Hansen | Ola | Timoteivn 10 | Sandnes |
2 | Svendson | Tove | Borgvn 23 | Sandnes |
3 | Pettersen | Kari | Storgt 20 | Stavanger |