2.3 ALTER TABLE
Description
Alters the schema of an existing table by adding new columns or modifying existing columns of the specified table.
Syntax
ALTER TABLE [ owner_name. ] table_name{ ADD [ new_column_name column_type [ NULL | NOT NULL ]| (new_column_name column_type [ NULL | NOT NULL ], ...) ]| MODIFY (column_name [ new_column_type ] [NULL | NOT NULL], ...)| DROP [ COLUMN ] { column_name | ( column_name , ...) }| ADD [ CONSTRAINT new_constraint_name ] table_constraint| DROP CONSTRAINT constraint_name} ;table_constraint ::PRIMARY KEY ( column [, ... ] )| UNIQUE ( column [, ... ] )| FOREIGN KEY ( column [, ... ] )REFERENCES [ owner_name. ] table_name [ ( column [, ... ] ) ]| CHECK ( search_condition )Notes
- Column additions and modifications have the following restrictions:
- A NOT NULL column can be added to a table only if the table does not contain any rows.
- The type can be modified or the length of the column can be decreased only if all the rows contain null values for the column being modified.
- An existing column can be made NOT NULL only if none of the rows contain a null value for that column.
- When a new column is added to an existing table, it is added after the existing columns for the table.
- Views that automatically refer to all the columns of a table (such as SELECT * FROM ...) need to be dropped and added to select any columns that have been added to the table after the view has been created.
- If you add a FOREIGN KEY constraint to an existing table, the table and column specified in the REFERENCES clause must exist before the constraint will work as expected. However, SQL does not check for the existence of the table and column specified in the REFERENCES clause. It is up to you to make sure they exist.
- When you drop a column, the following database objects dependent on that column are also automatically dropped:
However, views that include the column are not automatically dropped.
Examples
To add columns to the tmp table:
ISQL> ALTER TABLE tmpADD mname CHAR(8) ;ISQL> ALTER TABLE tmpADD (mname CHAR(8), nname CHAR(8)) ;To add table-level constraints, consider the table tmp consisting of integer fields, fld, fld1, fld2, and fld3.
ISQL> ALTER TABLE tmp ADD UNIQUE(fld) ;ISQL> ALTER TABLE tmp ADD primary key(fld1) ;ISQL> ALTER TABLE tmp ADD constraint fri_cns foreign key(fld2) ;ISQL> ALTER TABLE tmp ADD constraint chk_cns (fld2 > 10) ;Authorization
The user executing this statement must have any of the following privileges:
|
FairCom Corporation www.faircom.com |