SQL Getting Sta...login
SQL Getting Started Tutorial Manual
author:php.cn  update time:2022-04-12 14:15:40

SQL ALTER



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 columns to the table, please use the following syntax:

ALTER TABLE table_name
ADD column_name datatype

To delete a column in a table, use the following syntax (please note that some database systems do not allow this method of deleting columns in a database table):

ALTER TABLE table_name
DROP COLUMN column_name

To change the data type of a column in a table, use the following syntax:

SQL Server/MS Access:

ALTER TABLE table_name
ALTER COLUMN column_name datatype

My SQL/Oracle:

ALTER TABLE table_name
MODIFY COLUMN column_name datatype


##SQL ALTER TABLE example

Please see the "Persons" table:

P_IdLastNameFirstNameAddressCity1HansenOlaTimoteivn 10Sandnes2SvendsonToveBorgvn 23Sandnes3PettersenKariStorgt 20Stavanger
Now, we want to add a column called "DateOfBirth" to the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons
ADD DateOfBirth date
Please note that the type of the new column "DateOfBirth" It is date, which can store the date. The data type specifies the type of data that can be stored in the column. To learn about the data types available in MS Access, MySQL and SQL Server, visit our complete

Data Types Reference.

Now, the "Persons" table will look like this:

P_IdLastNameFirstNameAddressCityDateOfBirth##1##2SvendsonToveBorgvn 23SandnesPettersen
HansenOlaTimoteivn 10Sandnes

##3
Kari Storgt 20Stavanger


Change 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:

ALTER TABLE Persons
ALTER COLUMN DateOfBirth year

Please note that now the "DateOfBirth" column The type is year, which can store the year in 2-digit or 4-digit format.


DROP COLUMN Example

Next, we want to delete the "DateOfBirth" column in the "Person" table.

We use the following SQL statement:

ALTER TABLE Persons
DROP COLUMN DateOfBirth

Now, the "Persons" table will look like this :

P_IdLastNameFirstNameAddressCity
1HansenOlaTimoteivn 10Sandnes
2 SvendsonToveBorgvn 23Sandnes
3PettersenKariStorgt 20Stavanger