5.4.2. ALTER TABLE

Used for

altering the structure of a table.

Available in

DSQL, ESQL

Syntax

  1. ALTER TABLE tablename
  2. <operation> [, <operation> ...]
  3. <operation> ::=
  4. ADD <col_def>
  5. | ADD <tconstraint>
  6. | DROP colname
  7. | DROP CONSTRAINT constr_name
  8. | ALTER [COLUMN] colname <col_mod>
  9. <col_def> ::= <regular_col_def> | <computed_col_def>
  10. <regular_col_def> ::=
  11. colname {<datatype> | domainname}
  12. [DEFAULT {<literal> | NULL | <context_var>}]
  13. [NOT NULL]
  14. [<col_constraint>]
  15. [COLLATE collation_name]
  16. <computed_col_def> ::=
  17. colname [<datatype>]
  18. {COMPUTED [BY] | GENERATED ALWAYS AS} (<expression>)
  19. <col_mod> ::= <regular_col_mod> | <computed_col_mod>
  20. <regular_col_mod> ::=
  21. TO newname
  22. | POSITION newpos
  23. | TYPE {<datatype> | domainname}
  24. | SET DEFAULT {<literal> | NULL | <context_var>}
  25. | DROP DEFAULT
  26. <computed_col_mod> ::=
  27. TO newname
  28. | POSITION newpos
  29. | [TYPE <datatype>] {COMPUTED [BY] | GENERATED ALWAYS AS} (<expression>)
  30. <datatype> ::=
  31. {SMALLINT | INTEGER | BIGINT} [<array_dim>]
  32. | {FLOAT | DOUBLE PRECISION} [<array_dim>]
  33. | {DATE | TIME | TIMESTAMP} [<array_dim>]
  34. | {DECIMAL | NUMERIC} [(precision [, scale])] [<array_dim>]
  35. | {CHAR | CHARACTER} [VARYING] | VARCHAR} [(size)]
  36. [<array_dim>] [CHARACTER SET charset_name]
  37. | {NCHAR | NATIONAL {CHARACTER | CHAR}} [VARYING]
  38. [(size)] [<array_dim>]
  39. | BLOB [SUB_TYPE {subtype_num | subtype_name}]
  40. [SEGMENT SIZE seglen] [CHARACTER SET charset_name]
  41. | BLOB [(seglen [, subtype_num])]
  42. <array_dim> ::= '[' [m:]n [,[m:]n ...] ']'
  43. <col_constraint> ::=
  44. [CONSTRAINT constr_name]
  45. { PRIMARY KEY [<using_index>]
  46. | UNIQUE [<using_index>]
  47. | REFERENCES other_table [(colname)] [<using_index>]
  48. [ON DELETE {NO ACTION | CASCADE | SET DEFAULT | SET NULL}]
  49. [ON UPDATE {NO ACTION | CASCADE | SET DEFAULT | SET NULL}]
  50. | CHECK (<check_condition>) }
  51. <tconstraint> ::=
  52. [CONSTRAINT constr_name]
  53. { PRIMARY KEY (<col_list>) [<using_index>]
  54. | UNIQUE (<col_list>) [<using_index>]
  55. | FOREIGN KEY (<col_list>)
  56. REFERENCES other_table [(<col_list>)] [<using_index>]
  57. [ON DELETE {NO ACTION | CASCADE | SET DEFAULT | SET NULL}]
  58. [ON UPDATE {NO ACTION | CASCADE | SET DEFAULT | SET NULL}]
  59. | CHECK (<check_condition>) }
  60. <col_list> ::= colname [, colname ...]
  61. <using_index> ::= USING
  62. [ASC[ENDING] | DESC[ENDING]] INDEX indexname
  63. <check_condition> ::=
  64. <val> <operator> <val>
  65. | <val> [NOT] BETWEEN <val> AND <val>
  66. | <val> [NOT] IN (<val> [, <val> ...] | <select_list>)
  67. | <val> IS [NOT] NULL
  68. | <val> IS [NOT] DISTINCT FROM <val>
  69. | <val> [NOT] CONTAINING <val>
  70. | <val> [NOT] STARTING [WITH] <val>
  71. | <val> [NOT] LIKE <val> [ESCAPE <val>]
  72. | <val> [NOT] SIMILAR TO <val> [ESCAPE <val>]
  73. | <val> <operator> {ALL | SOME | ANY} (<select_list>)
  74. | [NOT] EXISTS (<select_expr>)
  75. | [NOT] SINGULAR (<select_expr>)
  76. | (<search_condition>)
  77. | NOT <search_condition>
  78. | <search_condition> OR <search_condition>
  79. | <search_condition> AND <search_condition>
  80. <operator> ::=
  81. <> | != | ^= | ~= | = | < | > | <= | >=
  82. | !< | ^< | ~< | !> | ^> | ~>
  83. <val> ::=
  84. colname ['['array_idx [, array_idx ...]']']
  85. | <literal>
  86. | <context_var>
  87. | <expression>
  88. | NULL
  89. | NEXT VALUE FOR genname
  90. | GEN_ID(genname, <val>)
  91. | CAST(<val> AS <datatype>)
  92. | (<select_one>)
  93. | func([<val> [, <val> ...]])
Table 23. ALTER TABLE Statement Parameters
ParameterDescription

tablename

Name (identifier) of the table

operation

One of the available operations altering the structure of the table

colname

Name (identifier) for a column in the table, max. 31 characters. Must be unique in the table.

newname

New name (identifier) for the column, max. 31 characters. Must be unique in the table.

newpos

The new column position (an integer between 1 and the number of columns in the table)

col_constraint

Column constraint

tconstraint

Table constraint

constr_name

The name (identifier) of a constraint. May consist of up to 31 characters.

other_table

The name of the table referenced by the foreign key constraint

literal

A literal value that is allowed in the given context

context_var

A context variable whose type is allowed in the given context

check_condition

The condition of a CHECK constraint that will be satisfied if it evaluates to TRUE or UNKNOWN/NULL

collation

Name of a collation sequence that is valid for charset_name, if it is supplied with datatype or, otherwise, is valid for the default character set of the database

array_dim

Array dimensions

m, n

Integer numbers defining the index range of an array dimension

precision

The total number of significant digits that a value of the datatype can hold (1..18)

scale

The number of digits after the decimal point (0..precision)

size

The maximum size of a string in characters

charset_name

The name of a valid character set, if the character set of the column is to be different to the default character set of the database

subtype_num

BLOB subtype number

subtype_name

BLOB subtype mnemonic name

seglen

Segment size (max. 65535)

select_one

A scalar SELECT statement — selecting one column and returning only one row

select_list

A SELECT statement selecting one column and returning zero or more rows

select_expr

A SELECT statement selecting one or more columns and returning zero or more rows

expression

An expression resolving to a value that is is allowed in the given context

genname

Sequence (generator) name

func

Internal function or UDF

The ALTER TABLE statement changes the structure of an existing table. With one ALTER TABLE statement it is possible to perform multiple operations, adding/dropping columns and constraints and also altering column specifications.

Multiple operations in an ALTER TABLE statement are separated with commas.

Version Count Increments

Some changes in the structure of a table increment the metadata change counter (“version count”) assigned to every table. The number of metadata changes is limited to 255 for each table. Once the counter reaches the 255 limit, you will not be able to make any further changes to the structure of the table without resetting the counter.

To reset the metadata change counter

You should back up and restore the database using the gbak utility.

The ADD Clause

With the ADD clause you can add a new column or a new table constraint. The syntax for defining the column and the syntax of defining the table constraint correspond with those described for CREATE TABLE statement.

Effect on Version Count

  • Each time a new column is added, the metadata change counter is increased by one

  • Adding a new table constraint does not increase the metadata change counter

Points to Be Aware of
  1. Be careful about adding a new column with the NOT NULL constraint set. It may lead to breaking the logical integrity of data, since you will have existing records containing NULL in a non-nullable column. When adding a non-nullable column, it is recommended either to set a default value for it or to update the column in existing rows with a non-null value.

  2. When a new CHECK constraint is added, existing data is not tested for compliance. Prior testing of existing data against the new CHECK expression is recommended.

The DROP Clause

The DROP *<column name>* clause deletes the specified column from the table. An attempt to drop a column will fail if anything references it. Consider the following items as sources of potential dependencies:

  • column or table constraints

  • indexes

  • stored procedures and triggers

  • views

Effect on Version Count

  • Each time a column is dropped, the table’s metadata change counter is increased by one.

The DROP CONSTRAINT Clause

The DROP CONSTRAINT clause deletes the specified column-level or table-level constraint.

A PRIMARY KEY or UNIQUE key constraint cannot be deleted if it is referenced by a FOREIGN KEY constraint in another table. It will be necessary to drop that FOREIGN KEY constraint before attempting to drop the PRIMARY KEY or UNIQUE key constraint it references.

Effect on Version Count

  • Deleting a column constraint or a table constraint does not increase the metadata change counter.

The ALTER [COLUMN] Clause

With the ALTER [COLUMN] clause, attributes of existing columns can be modified without the need to drop and re-add the column. Permitted modifications are:

  • change the name (does not affect the metadata change counter)

  • change the data type (increases the metadata change counter by one)

  • change the column position in the column list of the table (does not affect the metadata change counter)

  • delete the default column value (does not affect the metadata change counter)

  • set a default column value or change the existing default (does not affect the metadata change counter)

  • change the type and expression for a computed column (does not affect the metadata change counter)

Renaming a Column: the TO Keyword

The TO keyword with a new identifier renames an existing column. The table must not have an existing column that has the same identifier.

It will not be possible to change the name of a column that is included in any constraint: PRIMARY KEY, UNIQUE key, FOREIGN KEY, column constraint or the CHECK constraint of the table.

Renaming a column will also be disallowed if the column is used in any trigger, stored procedure or view.

Changing the Data Type of a Column: the TYPE Keyword

The keyword TYPE changes the data type of an existing column to another, allowable type. A type change that might result in data loss will be disallowed. As an example, the number of characters in the new type for a CHAR or VARCHAR column cannot be smaller than the existing specification for it.

If the column was declared as an array, no change to its type or its number of dimensions is permitted.

The data type of a column that is involved in a foreign key, primary key or unique constraint cannot be changed at all.

Changing the Position of a Column: the POSITION Keyword

The POSITION keyword changes the position of an existing column in the notional “left-to-right” layout of the record.

Numbering of column positions starts at 1.

  • If a position less than 1 is specified, an error message will be returned

  • If a position number is greater than the number of columns in the table, its new position will be adjusted silently to match the number of columns.

The DROP DEFAULT and SET DEFAULT Clauses

The optional DROP DEFAULT clause deletes the default value for the column if it was put there previously by a CREATE TABLE or ALTER TABLE statement.

  • If the column is based on a domain with a default value, the default value will revert to the domain default

  • An execution error will be raised if an attempt is made to delete the default value of a column which has no default value or whose default value is domain-based

The optional SET DEFAULT clause sets a default value for the column. If the column already has a default value, it will be replaced with the new one. The default value applied to a column always overrides one inherited from a domain.

The COMPUTED [BY] or GENERATED ALWAYS AS Clauses

The data type and expression underlying a computed column can be modified using a COMPUTED [BY] or GENERATED ALWAYS AS clause in the ALTER TABLE ALTER [COLUMN] statement. Converting a regular column to a computed one and vice versa are not permitted.

Attributes that Cannot Be Altered

The following alterations are not supported:

  • Enabling or disabling the NOT NULL constraint on a column

  • Changing the default collation for a character type column

Only the table owner and administrators have the authority to use ALTER TABLE.

Examples Using ALTER TABLE

  1. Adding the CAPITAL column to the COUNTRY table.

    1. ALTER TABLE COUNTRY
    2. ADD CAPITAL VARCHAR(25);
  2. Adding the CAPITAL column with the UNIQUE constraint and deleting the CURRENCY column.

    1. ALTER TABLE COUNTRY
    2. ADD CAPITAL VARCHAR(25) NOT NULL UNIQUE,
    3. DROP CURRENCY;
  3. Adding the CHK_SALARY check constraint and a foreign key to the JOB table.

    1. ALTER TABLE JOB
    2. ADD CONSTRAINT CHK_SALARY CHECK (MIN_SALARY < MAX_SALARY),
    3. ADD FOREIGN KEY (JOB_COUNTRY) REFERENCES COUNTRY (COUNTRY);
  4. Setting default value for the MODEL field, changing the type of the ITEMID column and renaming the MODELNAME column.

    1. ALTER TABLE STOCK
    2. ALTER COLUMN MODEL SET DEFAULT 1,
    3. ALTER COLUMN ITEMID TYPE BIGINT,
    4. ALTER COLUMN MODELNAME TO NAME;
  5. Changing the computed columns NEW_SALARY and SALARY_CHANGE.

    1. ALTER TABLE SALARY_HISTORY
    2. ALTER NEW_SALARY GENERATED ALWAYS AS
    3. (OLD_SALARY + OLD_SALARY * PERCENT_CHANGE / 100),
    4. ALTER SALARY_CHANGE COMPUTED BY
    5. (OLD_SALARY * PERCENT_CHANGE / 100);

See also

CREATE TABLE, DROP TABLE, CREATE DOMAIN