SQL Reference

CREATE TABLE

The CREATE TABLE statement defines a table. The definition must include its name and the names and attributes of its columns. The definition may include other attributes of the table, such as its primary key or check constraints.

Invocation

This statement can be embedded in an application program or issued through the use of dynamic SQL statements. It is an executable statement that can be dynamically prepared. However, if the bind option DYNAMICRULES BIND applies, the statement cannot be dynamically prepared (SQLSTATE 42509).

Authorization

The privileges held by the authorization ID of the statement must include at least one of the following:

To define a foreign key, the privileges held by the authorization ID of the statement must include one of the following on the parent table:

To define a summary table (using a fullselect) the privileges held by the authorization ID of the statement must include at least one of the following on each table or view identified in the fullselect:

Syntax

>>-CREATE--+----------+---TABLE--table-name--------------------->
           '-SUMMARY--'
 
>-----+-| element-list |------------------------------+--------->
      +-OF--type-name1--+--------------------------+--+
      |                 '-| typed-table-options |--'  |
      +-| summary-table-definition |------------------+
      '-LIKE--+-table-name1-+---+-------------------+-'
              +-view-name---+   '-| copy-options |--'
              '-nickname----'
 
        .-DATA CAPTURE NONE----.
>----*--+----------------------+--*----------------------------->
        '-DATA CAPTURE CHANGES-'
 
>-----+-----------------------------------------------+--*------>
      '-IN--tablespace-name1--| tablespace-options |--'
 
>-----+------------------------------------------------------------+>
      |                      .-,---------.                         |
      |                      V           |      .-USING HASHING--. |
      +-PARTITIONING KEY--(-----column---+---)--+----------------+-+
      '-REPLICATED-------------------------------------------------'
 
>----*--+----------------------+---*---------------------------><
        '-NOT LOGGED INITIALLY-'
 
element-list
 
       .-,---------------------------------.
       V                                   |
|---(------+-| column-definition |------+--+---)----------------|
           +-| unique-constraint |------+
           +-| referential-constraint |-+
           '-| check-constraint |-------'
 
typed-table-options
 
|---+----------------------------+---+-------------------------+->
    +-HIERARCHY--hierarchy-name--+   '-| typed-element-list |--'
    '-| under-clause |-----------'
 
>---------------------------------------------------------------|
 
under-clause
 
|---UNDER--supertable-name--INHERIT SELECT PRIVILEGES-----------|
 
typed-element-list
 
       .-,--------------------------------.
       V                                  |
|---(------+-| OID-column-definition |-+--+---)-----------------|
           +-| with-options |----------+
           +-| unique-constraint |-----+
           '-| check-constraint |------'
 
 
summary-table-definition
 
|--+----------------------------+---AS--(--fullselect--)--| summary-table-options |-->
   |    .-,--------------.      |
   |    V                |      |
   '-(-----column-name---+---)--'
 
>---------------------------------------------------------------|
 
summary-table-options
 
|---+-DEFINITION ONLY--+-------------------+-+------------------|
    |                  '-| copy-options |--' |
    '-| refreshable-table-options |----------'
 
copy-options
 
|---*----+----------------------------------------+--*---------->
         |                 .-COLUMN-.             |
         '--+-INCLUDING-+--+--------+--DEFAULTS---'
            '-EXCLUDING-'
 
                            .-COLUMN ATTRIBUTES-.
      .-EXCLUDING IDENTITY--+-------------------+--.
>-----+--------------------------------------------+--*---------|
      |                    .-COLUMN ATTRIBUTES-.   |
      '-INCLUDING IDENTITY-+-------------------+---'
 
refreshable-table-options
 
|---DATA INITIALLY--DEFERRED--REFRESH--+-DEFERRED--+------------>
                                       '-IMMEDIATE-'
 
        .-ENABLE QUERY OPTIMIZATION--.
>-------+----------------------------+--------------------------|
        '-DISABLE QUERY OPTIMIZATION-'
 
 
tablespace-options
 
|--+----------------------------------+------------------------->
   |                            (1)   |
   '-INDEX IN--tablespace-name2-------'
 
>-----+----------------------------+----------------------------|
      '-LONG IN--tablespace-name3--'
 
column-definition
 
|---column-name----+---------------------+---------------------->
                   |               (2)   |
                   '-| data-type |-------'
 
>-----+---------------------+-----------------------------------|
      '-| column-options |--'
 
column-options
 
    .---------------------------------------------------------------------------------.
    V                                                                                 |
|------+---------------------------------------------------------------------------+--+->
       +-NOT NULL------------------------------------------------------------------+
       |                 (3)                                                       |
       +-| lob-options |-----------------------------------------------------------+
       |                      (4)                                                  |
       +-| datalink-options |------------------------------------------------------+
       |                              (5)                                          |
       +-SCOPE--+-typed-table-name-+-----------------------------------------------+
       |        '-typed-view-name--'                                               |
       +-+-----------------------------------+---+-+-PRIMARY KEY-+---------------+-+
       | |            (6)                    |   | '-UNIQUE------'               | |
       | '-CONSTRAINT-------constraint-name--'   +-| references-clause |---------+ |
       |                                         '-CHECK--(--check-condition--)--' |
       |                         (7)                                               |
       +-| column-default-spec |---------------------------------------------------+
       |                        (8)                                                |
       '-INLINE LENGTH--integer----------------------------------------------------'
 
>---------------------------------------------------------------|
 

Notes:

  1. Specifying which table space will contain a table's index can only be done when the table is created.

  2. If the first column-option chosen is a column-default-spec with a generation-expression, then the data-type can be omitted. It will be determined from the resulting data type of the generation-expression.

  3. The lob-options clause only applies to large object types (BLOB, CLOB and DBCLOB) and distinct types based on large object types.

  4. The datalink-options clause only applies to the DATALINK type and distinct types based on the DATALINK type. The LINKTYPE URL clause is required for these types.

  5. The SCOPE clause only applies to the REF type.

  6. For compatibility with Version 1, the CONSTRAINT keyword may be omitted in a column-definition defining a references-clause.

  7. IDENTITY column attributes are not supported in an Extended Enterprise Edition (EEE) database with more than one partition.

  8. INLINE LENGTH only applies to columns defined as structured types.

 
data-type
 
|--+-SMALLINT-----------------------------------------------------------------------+->
   +-+-INTEGER-+--------------------------------------------------------------------+
   | '-INT-----'                                                                    |
   +-BIGINT-------------------------------------------------------------------------+
   +-+-FLOAT--+----------------+-+--------------------------------------------------+
   | |        '-(--integer--)--' |                                                  |
   | +-REAL----------------------+                                                  |
   | |        .-PRECISION-.      |                                                  |
   | '-DOUBLE-+-----------+------'                                                  |
   +--+-DECIMAL-+---+--------------------------------+------------------------------+
   |  +-DEC-----+   '-(--integer--+-----------+---)--'                              |
   |  +-NUMERIC-+                 '-,integer--'                                     |
   |  '-NUM-----'                                                                   |
   +--+--+-CHARACTER-+---+------------+----------------+---+----------------------+-+
   |  |  '-CHAR------'   '-(integer)--'                |   |  (1)                 | |
   |  +--+-VARCHAR-------------------+--(--integer--)--+   '--------FOR BIT DATA--' |
   |  |  '--+-CHARACTER-+---VARYING--'                 |                            |
   |  |     '-CHAR------'                              |                            |
   |  '-LONG VARCHAR-----------------------------------'                            |
   |                                                                                |
   +--+-BLOB---+--(--integer--+---+---)---------------------------------------------+
   |  +-CLOB---+              +-K-+                                                 |
   |  '-DBCLOB-'              +-M-+                                                 |
   |                          '-G-'                                                 |
   +-GRAPHIC--+------------+--------------------------------------------------------+
   |          '-(integer)--'                                                        |
   +-VARGRAPHIC--(integer)----------------------------------------------------------+
   +-LONG VARGRAPHIC----------------------------------------------------------------+
   +-DATE---------------------------------------------------------------------------+
   +-TIME---------------------------------------------------------------------------+
   +-TIMESTAMP----------------------------------------------------------------------+
   +-DATALINK--+----------------+---------------------------------------------------+
   |           '-(--integer--)--'                                                   |
   +-distinct-type-name-------------------------------------------------------------+
   +-structured-type-name-----------------------------------------------------------+
   '-REF--(type-name2)--------------------------------------------------------------'
 
>---------------------------------------------------------------|
 

Notes:

  1. The FOR BIT DATA clause may be specified in random order with the other column constraints that follow.

 
default-values
 
|--+-constant---------------------------------------------+-----|
   +-datetime-special-register----------------------------+
   +-USER-------------------------------------------------+
   +-NULL-------------------------------------------------+
   '-cast-function--(--+-constant------------------+---)--'
                       +-datetime-special-register-+
                       '-USER----------------------'
 
lob-options
 
       .-LOGGED-----.      .-NOT COMPACT--.
|---*--+------------+---*--+--------------+---*-----------------|
       '-NOT LOGGED-'      '-COMPACT------'
 
datalink-options
 
|---LINKTYPE URL------------------------------------------------>
 
     .-NO LINK CONTROL------------------------------.
>----+----------------------------------------------+-----------|
     '-FILE LINK CONTROL--+-| file-link-options |-+-'
                          '-MODE DB2OPTIONS-------'
 
file-link-options
 
|---*--INTEGRITY----ALL----*--READ PERMISSION--+-FS-+----------->
                                               '-DB-'
 
>----*--WRITE PERMISSION--+-FS------+--*--RECOVERY--+-NO--+----->
                          '-BLOCKED-'               '-YES-'
 
>----*--ON UNLINK--+-RESTORE-+---*------------------------------|
                   '-DELETE--'
 
column-default-spec
 
|---+-| default-clause |-----------------------------------------------+->
    '-GENERATED--+-ALWAYS-----+---AS--+-| identity-clause |----------+-'
                 '-BY DEFAULT-'       '-(--generation-expression--)--'
 
>---------------------------------------------------------------|
 
identity-clause
 
|---IDENTITY--+-------------------------------------------------------+->
              |    .-,-----------------------------------------.      |
              |    V                 .-1----------------.      |      |
              '-(------+-START WITH--+-numeric-constant-+---+--+---)--'
                       |               .-1----------------. |
                       +-INCREMENT BY--+-numeric-constant-+-+
                       | .-CACHE--20----------------.       |
                       '-+-NO CACHE-----------------+-------'
                         '-CACHE--integer-constant--'
 
>---------------------------------------------------------------|
 
 
references-clause
 
|--REFERENCES--table-name----+----------------------------+----->
                             |    .-,--------------.      |
                             |    V                |      |
                             '-(-----column-name---+---)--'
 
>-----| rule-clause |-------------------------------------------|
 
rule-clause
 
      .-ON DELETE NO ACTION-----.      .-ON UPDATE NO ACTION--.
|--*--+-------------------------+---*--+----------------------+---*-->
      '-ON DELETE--+-RESTRICT-+-'      '-ON UPDATE RESTRICT---'
                   +-CASCADE--+
                   '-SET NULL-'
 
>---------------------------------------------------------------|
 
default-clause
 
    .-WITH-.
|---+------+--DEFAULT--+---------------------+------------------|
                       '-| default-values |--'
 
unique-constraint
 
|---+------------------------------+---+-UNIQUE------+---------->
    '-CONSTRAINT--constraint-name--'   '-PRIMARY KEY-'
 
        .-,--------------.
        V                |
>----(-----column-name---+---)----------------------------------|
 
referential-constraint
 
|---+-----------------------------------+--FOREIGN KEY---------->
    |                             (1)   |
    '-CONSTRAINT--constraint-name-------'
 
        .-,--------------.
        V                |
>----(-----column-name---+---)----| references-clause |---------|
 
check-constraint
 
|--+------------------------------+----------------------------->
   '-CONSTRAINT--constraint-name--'
 
>----CHECK--(--check-condition--)-------------------------------|
 
OID-column-definition
 
|---REF IS--OID-column-name--USER GENERATED---------------------|
 
with-options
 
|---column-name--WITH OPTIONS---| column-options |--------------|
 

Notes:

  1. For compatibility with Version 1, constraint-name may be specified following FOREIGN KEY (without the CONSTRAINT keyword).

Description

SUMMARY
Indicates that a summary table is being defined. The keyword is optional, but when specified, the statement must include a summary-table-definition (SQLSTATE 42601).

table-name
Names the table. The name, including the implicit or explicit qualifier, must not identify a table, view, or alias described in the catalog. The schema name must not be SYSIBM, SYSCAT, SYSFUN, or SYSSTAT (SQLSTATE 42939).

OF type-name1
Specifies that the columns of the table are based on the attributes of the structured type identified by type-name1. If type-name1 is specified without a schema name, the type name is resolved by searching the schemas on the SQL path (defined by the FUNCPATH preprocessing option for static SQL and by the CURRENT PATH register for dynamic SQL). The type name must be the name of an existing user-defined type (SQLSTATE 42704) and it must be an instantiable structured type (SQLSTATE 428DP) with at least one attribute (SQLSTATE 42997).

If UNDER is not specified, an object identifier column must be specified (refer to the OID-column-definition). This object identifier column is the first column of the table. The object ID column is followed by columns based on the attributes of type-name1.

HIERARCHY hierarchy-name
Names the hierarchy table associated with the table hierarchy. It is created at the same time as the root table of the hierarchy. The data for all subtables in the typed table hierarchy is stored in the hierarchy table. A hierarchy table cannot be directly referenced in SQL statements. A hierarchy-name is a table-name. The hierarchy-name, including the implicit or explicit schema name, must not identify a table, nickname, view, or alias described in the catalog. If the schema name is specified, it must be the same as the schema name of the table being created (SQLSTATE 428DQ). If this clause is omitted when defining the root table, a name is generated by the system consisting of the name of the table being created followed by a unique suffix such that the identifier is unique within the identifiers of the existing tables, views, aliases, and nicknames.

UNDER supertable-name
Indicates that the table is a subtable of supertable-name. The supertable must be an existing table (SQLSTATE 42704) and the table must be defined using a structured type that is the immediate supertype of type-name1 (SQLSTATE 428DB). The schema name of table-name and supertable-name must be the same (SQLSTATE 428DQ). The table identified by supertable-name must not have any existing subtable already defined using type-name1 (SQLSTATE 42742).

The columns of the table include the object identifier column of the supertable with its type modified to be REF(type-name1), followed by columns based on the attributes of type-name1 (remember that the type includes the attributes of its supertype). The attribute names cannot be the same as the OID column name (SQLSTATE 42711).

Other table options including table space, data capture, not logged initially and partitioning key options cannot be specified. These options are inherited from the supertable (SQLSTATE 42613).

INHERIT SELECT PRIVILEGES
Any user or group holding a SELECT privilege on the supertable will be granted an equivalent privilege on the newly created subtable. The subtable definer is considered to be the grantor of this privilege.

element-list
Defines the elements of a table. This includes the definition of columns and constraints on the table.

typed-element-list
Defines the additional elements of a typed table. This includes the additional options for the columns, the addition of an object identifier column (root table only), and constraints on the table.

summary-table-definition
If the table definition is based on the result of a query, then the table is a summary table based on the query.

column-name
Names the columns in the table. If a list of column names is specified, it must consist of as many names as there are columns in the result table of the fullselect. Each column-name must be unique and unqualified. If a list of column names is not specified, the columns of the table inherit the names of the columns of the result table of the fullselect.

A list of column names must be specified if the result table of the fullselect has duplicate column names of an unnamed column (SQLSTATE 42908). An unnamed column is a column derived from a constant, function, expression, or set operation that is not named using the AS clause of the select list.

AS
Introduces the query that is used for the definition of the table and to determine the data included in the table.

fullselect
Defines the query in which the table is based. The resulting column definitions are the same as those for a view defined with the same query.

Every select list element must have a name (use the AS clause for expressions - see select-clause for details) . The summary-table-options specified define attributes of the summary table. The option chosen also defines the contents of the fullselect as follows.

When DEFINITION ONLY is specified, any valid fullselect that does not reference a typed table or typed view can be specified.

When REFRESH DEFERRED or REFRESH IMMEDIATE is specified, the fullselect cannot include (SQLSTATE 428EC):

  • references to a nickname, summary table, declared temporary table, or typed table in any FROM clause
  • references to a view where the fullselect of the view violates any of the listed restrictions on the fullselect of the summary table
  • expressions that are a reference type or DATALINK type (or distinct type based on these types)
  • functions that have external action
  • functions written in SQL
  • functions that depend on physical characteristics (for example NODENUMBER, PARTITION)
  • table or view references to system objects (explain tables also should not be specified)
  • expressions that are a structured type or LOB type (or a distinct type based on a LOB type)

When REFRESH IMMEDIATE is specified:

  • the fullselect must be a subselect
  • the subselect cannot include:
    • functions that are not deterministic
    • scalar fullselects
    • predicates with fullselects
    • special registers
  • a GROUP BY clause must be included in the subselect unless the summary table is REPLICATED.
  • The supported column functions are SUM, COUNT, COUNT_BIG and GROUPING (without DISTINCT). The select list must contain a COUNT(*) or COUNT_BIG(*) column. If the summary table select list contains SUM(X) where X is a nullable argument, then the summary table must also have COUNT(X) in its select list. These column functions cannot be part of any expressions.
  • if the FROM clause references more than one table or view, it can only define an inner join without using the explicit INNER JOIN syntax
  • all GROUP BY items must be included in the select list
  • GROUPING SETS, CUBE and ROLLUP are supported. The GROUP BY items and associated GROUPING column functions in the select list must form a unique key of the result set. Thus, the following restrictions must be satisfied:
    • no grouping sets may be repeated. For example, ROLLUP(X,Y), X is not allowed because it is equivalent to GROUPING SETS((X,Y),(X),(X))
    • if X is a nullable GROUP BY item that appears within GROUPING SETS, CUBE, or ROLLUP, then GROUPING(X) must appear in the select list
    • grouping on constants is not allowed
  • a HAVING clause is not allowed
  • if in a multiple partition nodegroup, then a partitioning key must be a subset of the group by items, or the summary table must be replicated.

summary-table-options
Define the attributes of the summary table.

DEFINITION ONLY
The query is used only to define the table. The table is not populated using the results of query and the REFRESH TABLE statement cannot be used. When the CREATE TABLE statement is completed, the table is no longer considered a summary table.

The columns of the table are defined based on the definitions of the columns that result from the fullselect. If the fullselect references a single table in the FROM clause, select list items that are columns of that table are defined using the column name, data type, and nullability characteristic of the referenced table.

refreshable-table-options
Define the refreshable options of the summary table attributes.

DATA INITIALLY DEFERRED
Data is not inserted into the table as part of the CREATE TABLE statement. A REFRESH TABLE statement specifying the table-name is used to insert data into the table.

REFRESH
Indicates how the data in the table is maintained.

DEFERRED
The data in the table can be refreshed at any time using the REFRESH TABLE statement. The data in the table only reflects the result of the query as a snapshot at the time the REFRESH TABLE statement is processed. Summary tables defined with this attribute do not allow INSERT, UPDATE or DELETE statements (SQLSTATE 42807).

IMMEDIATE
The changes made to the underlying tables as part of a DELETE, INSERT, or UPDATE are cascaded to the summary table. In this case, the content of the table, at any point-in-time, is the same as if the specified subselect is processed. Summary tables defined with this attribute do not allow INSERT, UPDATE, or DELETE statements (SQLSTATE 42807).

ENABLE QUERY OPTIMIZATION
The summary table can be used for query optimization under appropriate circumstances.

DISABLE QUERY OPTIMIZATION
The summary table will not be used for query optimization. The table can still be queried directly.

LIKE table-name1 or view-name or nickname
Specifies that the columns of the table have exactly the same name and description as the columns of the identified table (table-name1), view (view-name) or nickname (nickname). The name specified after LIKE must identify a table, view or nickname that exists in the catalog, or a declared temporary table. A typed table or typed view cannot be specified (SQLSTATE 428EC).

The use of LIKE is an implicit definition of n columns, where n is the number of columns in the identified table, view or nickname.

Column default and identity column attributes may be included or excluded, based on the copy-attributes clauses. The implicit definition does not include any other attributes of the identified table, view or nickname. Thus the new table does not have any unique constraints, foreign key constraints, triggers, or indexes. The table is created in the table space implicitly or explicitly specified by the IN clause, and the table has any other optional clause only if the optional clause is specified.

copy-options
These options specify whether or not to copy additional attributes of the source result table definition (table, view or fullselect).

INCLUDING COLUMN DEFAULTS
Column defaults for each updatable column of the source result table definition are copied. Columns that are not updatable will not have a default defined in the corresponding column of the created table.

If LIKE table-name is specified and table-name identifies a base table or declared temporary table, then INCLUDING COLUMN DEFAULTS is the default.

EXCLUDING COLUMN DEFAULTS
Columns defaults are not copied from the source result table definition.

This clause is the default, except when LIKE table-name is specified and table-name identifies a base table or declared temporary table.

INCLUDING IDENTITY COLUMN ATTRIBUTES
Identity column attributes (START WITH, INCREMENT BY, and CACHE values) are copied from the source result table definition, if possible. It is possible to copy the identity column attributes, if the element of the corresponding column in the table, view, or fullselect is the name of a table column, or the name of a view column which directly or indirectly maps to the name of a base table column with the identity property. In all other cases, the columns of the new table will not get the identity property. For example:
  • the select-list of the fullselect includes multiple instances of an identity column name (that is, selecting the same column more than once)
  • the select list of the fullselect includes multiple identity columns (that is, it involves a join)
  • the identity column is included in an expression in the select list
  • the fullselect includes a set operation (union, except, or intersect).

EXCLUDING IDENTITY COLUMN ATTRIBUTES
Identity column attributes are not copied from the source result table definition.

column-definition
Defines the attributes of a column.

column-name
Names a column of the table. The name cannot be qualified and the same name cannot be used for more than one column of the table.

A table may have the following:

  • a 4K page size with maximum of 500 columns where the byte counts of the columns must not be greater than 4005 in a 4K page size. Refer to Row Size for more details.
  • an 8K page size with maximum of 1 012 columns where the byte counts of the columns must not be greater than 8101. Refer to Row Size for more details.
  • an 16K page size with maximum of 1 012 columns where the byte counts of the columns must not be greater than 16 293.
  • an 32K page size with maximum of 1 012 columns where the byte counts of the columns must not be greater than 32 677.

data-type
Is one of the types in the following list. Use:

SMALLINT
For a small integer.

INTEGER  or  INT
For a large integer.

BIGINT
For a big integer.

FLOAT(integer)
For a single or double precision floating-point number, depending on the value of the integer. The value of the integer must be in the range 1 through 53. The values 1 through 24 indicate single precision and the values 25 through 53 indicate double precision.

You can also specify:

REAL
For single precision floating-point.
DOUBLE
For double precision floating-point.
DOUBLE PRECISION
For double precision floating-point.
FLOAT
For double precision floating-point.

DECIMAL(precision-integer, scale-integer)  or  DEC(precision-integer, scale-integer)
For a decimal number. The first integer is the precision of the number; that is, the total number of digits; it may range from 1 to 31. The second integer is the scale of the number; that is, the number of digits to the right of the decimal point; it may range from 0 to the precision of the number.

If precision and scale are not specified, the default values of 5,0 are used. The words NUMERIC and NUM can be used as synonyms for DECIMAL and DEC.

CHARACTER(integer)  or  CHAR(integer)  or  CHARACTER  or  CHAR
For a fixed-length character string of length integer, which may range from 1 to 254. If the length specification is omitted, a length of 1 character is assumed.

VARCHAR(integer),  or  CHARACTER VARYING(integer),  or  CHAR VARYING(integer)
For a varying-length character string of maximum length integer, which may range from 1 to 32 672.

LONG VARCHAR
For a varying-length character string with a maximum length of 32700.

FOR BIT DATA
Specifies that the contents of the column are to be treated as bit (binary) data. During data exchange with other systems, code page conversions are not performed. Comparisons are done in binary, irrespective of the database collating sequence.

BLOB(integer [K | M | G])
For a binary large object string of the specified maximum length in bytes.

The length may be in the range of 1 byte to 2 147 483 647 bytes.

If integer by itself is specified, that is the maximum length.

If integer K (in either upper or lower case) is specified, the maximum length is 1 024 times integer. The maximum value for integer is 2 097 152.

If integer M is specified, the maximum length is 1 048 576 times integer. The maximum value for integer is 2 048.

If integer G is specified, the maximum length is 1 073 741 824 times integer. The maximum value for integer is 2.

To create BLOB strings greater than 1 gigabyte, you must specify the NOT LOGGED option.

Any number of spaces is allowed between the integer and K, M, or G. Also, no space is required. For example, all the following are valid.

   BLOB(50K)    BLOB(50 K)    BLOB (50   K)

CLOB(integer [K | M | G]) 74
For a character large object string of the specified maximum length in bytes.

The meaning of the integer K | M | G is the same as for BLOB.

To create CLOB strings greater than 1 gigabyte, you must specify the NOT LOGGED option.

DBCLOB(integer [K | M | G])
For a double-byte character large object string of the specified maximum length in double-byte characters.

The meaning of the integer K | M | G is similar to that for BLOB. The differences are that the number specified is the number of double-byte characters and that the maximum size is 1 073 741 823 double-byte characters.

To create DBCLOB strings greater than 1 gigabyte, you must specify the NOT LOGGED option.

GRAPHIC(integer)
For a fixed-length graphic string of length integer which may range from 1 to 127. If the length specification is omitted, a length of 1 is assumed.

VARGRAPHIC(integer)
For a varying-length graphic string of maximum length integer, which may range from 1 to 16 336.

LONG VARGRAPHIC
For a varying-length graphic string with a maximum length of 16 350.

DATE
For a date.

TIME
For a time.

TIMESTAMP
For a timestamp.

DATALINK  or  DATALINK(integer)
For a link to data stored outside the database.

The column in the table consists of "anchor values" that contain the reference information that is required to establish and maintain the link to the external data as well as an optional comment.

The length of a DATALINK column is 200 bytes. If integer is specified, it must be 200. If the length specification is omitted, a length of 200 bytes is assumed.

A DATALINK value is an encapsulated value with a set of built-in scalar functions. There is a function called DLVALUE to create a DATALINK value. The following functions can be used to extract attributes from a DATALINK value.

  • DLCOMMENT
  • DLLINKTYPE
  • DLURLCOMPLETE
  • DLURLPATH
  • DLURLPATHONLY
  • DLURLSCHEME
  • DLURLSERVER

A DATALINK column has the following restrictions:

  • The column cannot be part of any index. Therefore, it cannot be included as a column of a primary key or unique constraint (SQLSTATE 42962).
  • The column cannot be a foreign key of a referential constraint (SQLSTATE 42830).
  • A default value (WITH DEFAULT) cannot be specified for the column. If the column is nullable, the default for the column is NULL (SQLSTATE 42894).

distinct-type-name
For a user-defined type that is a distinct type. If a distinct type name is specified without a schema name, the distinct type name is resolved by searching the schemas on the SQL path (defined by the FUNCPATH preprocessing option for static SQL and by the CURRENT PATH register for dynamic SQL).

If a column is defined using a distinct type, then the data type of the column is the distinct type. The length and the scale of the column are respectively the length and the scale of the source type of the distinct type.

If a column defined using a distinct type is a foreign key of a referential constraint, then the data type of the corresponding column of the primary key must have the same distinct type.

structured-type-name
For a user-defined type that is a structured type. If a structured type name is specified without a schema name, the structured type name is resolved by searching the schemas on the SQL path (defined by the FUNCPATH preprocessing option for static SQL, and by the CURRENT PATH register for dynamic SQL).

If a column is defined using a structured type, then the static data type of the column is the structured type. The column may include values with a dynamic type that is a subtype of structured-type-name.

A column defined using a structured type cannot be used in a primary key, unique constraint, foreign key, index key or partitioning key (SQLSTATE 42962).

If a column is defined using a structured type, and contains a reference-type attribute at any level of nesting, that reference-type attribute is unscoped. To use such an attribute in a dereference operation, it is necessary to specify a SCOPE explicitly, using a CAST specification.

If a column is defined using a structured type with an attribute of type DATALINK, or a distinct type sourced on DATALINK, this column can only be null. An attempt to use the constructor function for this type will return an error (SQLSTATE 428ED) and so no instance of this type can be inserted into the column.

REF (type-name2)
For a reference to a typed table. If type-name2 is specified without a schema name, the type name is resolved by searching the schemas on the SQL path (defined by the FUNCPATH preprocessing option for static SQL and by the CURRENT PATH register for dynamic SQL). The underlying data type of the column is based on the representation data type specified in the REF USING clause of the CREATE TYPE statement for type-name2 or the root type of the data type hierarchy that includes type-name2.

column-options
Defines additional options related to columns of the table.

NOT NULL
Prevents the column from containing null values.

If NOT NULL is not specified, the column can contain null values, and its default value is either the null value or the value provided by the WITH DEFAULT clause.

lob-options
Specifies options for LOB data types.

LOGGED
Specifies that changes made to the column are to be written to the log. The data in such columns is then recoverable with database utilities (such as RESTORE DATABASE). LOGGED is the default.

LOBs greater than 1 gigabyte cannot be logged (SQLSTATE 42993) and LOBs greater than 10 megabytes should probably not be logged.

NOT LOGGED
Specifies that changes made to the column are not to be logged.

NOT LOGGED has no effect on a commit or rollback operation; that is, the database's consistency is maintained even if a transaction is rolled back, regardless of whether or not the LOB value is logged. The implication of not logging is that during a roll forward operation, after a backup or load operation, the LOB data will be replaced by zeros for those LOB values that would have had log records replayed during the roll forward. During crash recovery, all committed changes and changes rolled back will reflect the expected results. See the Administration Guide for the implications of not logging LOB columns.

COMPACT
Specifies that the values in the LOB column should take up minimal disk space (free any extra disk pages in the last group used by the LOB value), rather than leave any leftover space at the end of the LOB storage area that might facilitate subsequent append operations. Note that storing data in this way may cause a performance penalty in any append (length-increasing) operations on the column.

NOT COMPACT
Specifies some space for insertions to assist in future changes to the LOB values in the column. This is the default.

datalink-options
Specifies the options associated with a DATALINK data type.

LINKTYPE URL
This defines the type of link as a Uniform Resource Locator (URL).

NO LINK CONTROL
Specifies that there will not be any check made to determine that the file exists. Only the syntax of the URL will be checked. There is no database manager control over the file.

FILE LINK CONTROL
Specifies that a check should be made for the existence of the file. Additional options may be used to give the database manager further control over the file.

file-link-options
Additional options to define the level of database manager control of the file link.

INTEGRITY
Specifies the level of integrity of the link between a DATALINK value and the actual file.

ALL
Any file specified as a DATALINK value is under the control of the database manager and may NOT be deleted or renamed using standard file system programming interfaces.

READ PERMISSION
Specifies how permission to read the file specified in a DATALINK value is determined.

FS
The read access permission is determined by the file system permissions. Such files can be accessed without retrieving the file name from the column.

DB
The read access permission is determined by the database. Access to the file will only be allowed by passing a valid file access token, returned on retrieval of the DATALINK value from the table, in the open operation.

WRITE PERMISSION
Specifies how permission to write to the file specified in a DATALINK value is determined.

FS
The write access permission is determined by the file system permissions. Such files can be accessed without retrieving the file name from the column.

BLOCKED
Write access is blocked. The file cannot be directly updated through any interface. An alternative mechanism must be used to cause updates to the information. For example, the file is copied, the copy updated, and then the DATALINK value updated to point to the new copy of the file.

RECOVERY
Specifies whether or not DB2 will support point in time recovery of files referenced by values in this column.

YES
DB2 will support point in time recovery of files referenced by values in this column. This value can only be specified when INTEGRITY ALL and WRITE PERMISSION BLOCKED are also specified.

NO
Specifies that point in time recovery will not be supported.

ON UNLINK
Specifies the action taken on a file when a DATALINK value is changed or deleted (unlinked). Note that this is not applicable when WRITE PERMISSION FS is used.

RESTORE
Specifies that when a file is unlinked, the DataLink File Manager will attempt to return the file to the owner with the permissions that existed at the time the file was linked. In the case where the user is no longer registered with the file server, the result is product-specific. 75 This can only be specified when INTEGRITY ALL and WRITE PERMISSION BLOCKED are also specified.

DELETE
Specifies that the file will be deleted when it is unlinked. This can only be specified when READ PERMISSION DB and WRITE PERMISSION BLOCKED are also specified.

MODE DB2OPTIONS
This mode defines a set of default file link options. The defaults defined by DB2OPTIONS are:
  • INTEGRITY ALL
  • READ PERMISSION FS
  • WRITE PERMISSION FS
  • RECOVERY NO

ON UNLINK is not applicable since WRITE PERMISSION FS is used.

SCOPE
Identifies the scope of the reference type column.

A scope must be specified for any column that is intended to be used as the left operand of a dereference operator or as the argument of the DEREF function. Specifying the scope for a reference type column may be deferred to a subsequent ALTER TABLE statement to allow the target table to be defined, usually in the case of mutually referencing tables.

typed-table-name
The name of a typed table. The table must already exist or be the same as the name of the table being created (SQLSTATE 42704). The data type of column-name must be REF(S), where S is the type of typed-table-name (SQLSTATE 428DM). No checking is done of values assigned to column-name to ensure that the values actually reference existing rows in typed-table-name.

typed-view-name
The name of a typed view. The view must already exist or be the same as the name of the view being created (SQLSTATE 42704). The data type of column-name must be REF(S), where S is the type of typed-view-name (SQLSTATE 428DM). No checking is done of values assigned to column-name to ensure that the values actually reference existing rows in typed-view-name.

CONSTRAINT constraint-name
Names the constraint. A constraint-name must not identify a constraint that was already specified within the same CREATE TABLE statement. (SQLSTATE 42710).

If this clause is omitted, an 18-character identifier unique within the identifiers of the existing constraints defined on the table, is generated 76 by the system.

When used with a PRIMARY KEY or UNIQUE constraint, the constraint-name may be used as the name of an index that is created to support the constraint.

PRIMARY KEY
This provides a shorthand method of defining a primary key composed of a single column. Thus, if PRIMARY KEY is specified in the definition of column C, the effect is the same as if the PRIMARY KEY(C) clause is specified as a separate clause.

A primary key cannot be specified if the table is a subtable (SQLSTATE 429B3) since the primary key is inherited from the supertable.

See PRIMARY KEY within the description of the unique-constraint below.

UNIQUE
This provides a shorthand method of defining a unique key composed of a single column. Thus, if UNIQUE is specified in the definition of column C, the effect is the same as if the UNIQUE(C) clause is specified as a separate clause.

A unique constraint cannot be specified if the table is a subtable (SQLSTATE 429B3) since unique constraints are inherited from the supertable.

See UNIQUE within the description of the unique-constraint below.

references-clause
This provides a shorthand method of defining a foreign key composed of a single column. Thus, if a references-clause is specified in the definition of column C, the effect is the same as if that references-clause were specified as part of a FOREIGN KEY clause in which C is the only identified column.

See references-clause under referential-constraint below.

CHECK (check-condition)
This provides a shorthand method of defining a check constraint that applies to a single column. See CHECK (check-condition) below.

INLINE LENGTH integer
This option is only valid for a column defined using a structured type (SQLSTATE 42842) and indicates the maximum byte size of an instance of a structured type to store inline with the rest of the values in the row. Instances of structured types that cannot be stored inline are stored separately from the base table row, similar to the way that LOB values are handled. This takes place automatically.

The default INLINE LENGTH for a structured-type column is the inline length of its type (specified explicitly or by default in the CREATE TYPE statement). If INLINE LENGTH of the structured type is less than 292, the value 292 is used for the INLINE LENGTH of the column.
Note:The inline lengths of subtypes are not counted in the default inline length, meaning that instances of subtypes may not fit inline unless an explicit INLINE LENGTH is specified at CREATE TABLE time to account for existing and future subtypes.

The explicit INLINE LENGTH value must be at least 292 and cannot exceed 32672 (SQLSTATE 54010).

column-default-spec

default-clause
Specifies a default value for the column.

WITH
An optional keyword.

DEFAULT
Provides a default value in the event a value is not supplied on INSERT or is specified as DEFAULT on INSERT or UPDATE. If a default value is not specified following the DEFAULT keyword, the default value depends on the data type of the column as shown in Table 19.

If a column is defined as a DATALINK, then a default value cannot be specified (SQLSTATE 42613). The only possible default is NULL.

If the column is based on a column of a typed table, a specific default value must be specified when defining a default. A default value cannot be specified for the object identifier column of a typed table (SQLSTATE 42997).

If a column is defined using a distinct type, then the default value of the column is the default value of the source data type cast to the distinct type.

If a column is defined using a structured type, the default-clause cannot be specified (SQLSTATE 42842).

Omission of DEFAULT from a column-definition results in the use of the null value as the default for the column. If such a column is defined NOT NULL, then the column does not have a valid default.

default-values
Specific types of default values that can be specified are as follows.

constant
Specifies the constant as the default value for the column. The specified constant must:
  • represent a value that could be assigned to the column in accordance with the rules of assignment as described in Chapter 3
  • not be a floating-point constant unless the column is defined with a floating-point data type
  • not have non-zero digits beyond the scale of the column data type if the constant is a decimal constant (for example, 1.234 cannot be the default for a DECIMAL(5,2) column)
  • be expressed with no more than 254 characters including the quote characters, any introducer character such as the X for a hexadecimal constant, and characters from the fully qualified function name and parentheses when the constant is the argument of a cast-function.

datetime-special-register
Specifies the value of the datetime special register (CURRENT DATE, CURRENT TIME, or CURRENT TIMESTAMP) at the time of INSERT or UPDATE as the default for the column. The data type of the column must be the data type that corresponds to the special register specified (for example, data type must be DATE when CURRENT DATE is specified).

USER
Specifies the value of the USER special register at the time of INSERT or UPDATE as the default for the column. If USER is specified, the data type of the column must be a character string with a length not less than the length attribute of USER.

NULL
Specifies NULL as the default for the column. If NOT NULL was specified, DEFAULT NULL may be specified within the same column definition but will result in an error on any attempt to set the column to the default value.

cast-function
This form of a default value can only be used with columns defined as a distinct type, BLOB or datetime (DATE, TIME or TIMESTAMP) data type. For distinct type, with the exception of distinct types based on BLOB or datetime types, the name of the function must match the name of the distinct type for the column. If qualified with a schema name, it must be the same as the schema name for the distinct type. If not qualified, the schema name from function resolution must be the same as the schema name for the distinct type. For a distinct type based on a datetime type, where the default value is a constant, a function must be used and the name of the function must match the name of the source type of the distinct type with an implicit or explicit schema name of SYSIBM. For other datetime columns, the corresponding datetime function may also be used. For a BLOB or a distinct type based on BLOB, a function must be used and the name of the function must be BLOB with an implicit or explicit schema name of SYSIBM. For an example of using the cast-function, see ***.

constant
Specifies a constant as the argument. The constant must conform to the rules of a constant for the source type of the distinct type or for the data type if not a distinct type. If the cast-function is BLOB, the constant must be a string constant.

datetime-special-register
Specifies CURRENT DATE, CURRENT TIME, or CURRENT TIMESTAMP. The source type of the distinct type of the column must be the data type that corresponds to the specified special register.

USER
Specifies the USER special register. The data type of the source type of the distinct type of the column must be a string data type with a length of at least 8 bytes. If the cast-function is BLOB, the length attribute must be at least 8 bytes.

If the value specified is not valid, an error (SQLSTATE 42894) is raised.

GENERATED
Indicates that DB2 generates values for the column. You must specify GENERATED if the column is to be considered a generated column or an IDENTITY column.

ALWAYS
Indicates that DB2 will always generate a value for the column when a row is inserted into the table or whenever the result value of the generation-expression may change. The result of the expression is stored in the table. GENERATED ALWAYS is the recommended value unless you are using data propagation, or doing unload and reload operations. GENERATED ALWAYS is the required value for generated columns.

BY DEFAULT
Indicates that DB2 will generate a value for the column when a row is inserted into the table, unless a value is specified. BY DEFAULT is the recommended value when using data propagation or doing unload/reload.

Although not explicitly required, a unique, single-column index should be defined on the generated column to ensure uniqueness of the values.

AS IDENTITY
Specifies that the column is to be the identity column for this table. 77 A table can only have a single IDENTITY column (SQLSTATE 428C1). The IDENTITY keyword can only be specified if the data-type associated with the column is an exact numeric type 78 with a scale of zero, or a user-defined distinct type for which the source type is an exact numeric type with a scale of zero (SQLSTATE 42815).

An identity column is implicitly NOT NULL.

START WITH numeric-constant
Specifies the first value for the identity column. This value can be any positive or negative value that could be assigned to this column (SQLSTATE 42820) as long as there are no non-zero digits to the right of the decimal point (SQLSTATE 42894). The default is 1.

INCREMENT BY numeric-constant
Specifies the interval between consecutive values of the identity column. This value can be any positive or negative value that could be assigned to this column (SQLSTATE 42820). This value cannot be zero and cannot exceed the value of a large integer constant (SQLSTATE 428125), provided that there are no non-zero digits to the right of the decimal point (SQLSTATE 42894).

If this value is negative, then the sequence of values for this identity column descends. If this value is positive, then the sequence of values for this identity column ascends. The default is 1.

CACHE or NO CACHE
Specifies whether to keep some pre-allocated values in memory for faster access. If a new value is needed for the identity column, and there are none available in the cache, then the end of the new cache block must be logged. However, when a new value is needed for the identity column, and there is an unused value in the cache, then the allocation of that identity value is quicker, since no logging is necessary. This is a performance and tuning option.

CACHE integer-constant
Specifies how many values of the identity sequence that DB2 pre-allocates and keeps in memory. Pre-allocating and storing values in the cache reduces logging when values are generated for the identity column.

If a new value is needed for the identity column and there are none available in the cache, then the allocation of the value involves waiting for the log. However, when a new value is needed for the identity column and there is an unused value in the cache, the allocation of that identity value can be made quicker by not performing the logging.

In the event of a database deactivation, either normally 79 or due to a system failure, all cached sequence values that have not been used in committed statements are lost. The value specified for the CACHE option is the maximum number of values for the identity column that could be lost in case of database deactivation.

The minimum value is 2 and the maximum value is 32767 (SQLSTATE 42815). The default is CACHE 20.

NO CACHE
Specifies that values for the identity column are not to be pre-allocated.

When this option is specified, the values of the identity column are not stored in the cache. In this case, every request for a new identity value results in logging.

AS (generation-expression)
Specifies that the definition of the column is based on an expression. 80 The generation-expression cannot contain any of the following (SQLSTATE 42621):
  • subqueries
  • column functions
  • dereference operations or DEREF functions
  • user-defined or built-in functions that are non-deterministic
  • user-defined functions using the EXTERNAL ACTION option
  • user-defined functions using the SCRATCHPAD option
  • user-defined functions using the READS SQL DATA option
  • host variables or parameter markers
  • special registers
  • references to columns defined later in the column list
  • references to other generated columns

The data type for the column is based on the result data type of the generation-expression. A CAST specification can be used to force a particular data type and to provide a scope (for a reference type only). If data-type is specified, values are assigned to the column under the assignment rules described in Language Elements. A generated column is implicitly considered nullable, unless the NOT NULL column option is used. The data type of a generated column must be one for which equality is defined. This excludes columns of LONG VARCHAR, LONG VARGRAPHIC, LOB data types, DATALINKs, structured types, and distinct types based on any of these types (SQLSTATE 42962).

OID-column-definition
Defines the object identifier column for the typed table.

REF IS OID-column-name USER GENERATED
Specifies that an object identifier (OID) column is defined in the table as the first column. An OID is required for the root table of a table hierarchy (SQLSTATE 428DX). The table must be a typed table (the OF clause must be present) that is not a subtable (SQLSTATE 42613). The name for the column is defined as OID-column-name and cannot be the same as the name of any attribute of the structured type type-name1 (SQLSTATE 42711). The column is defined with type REF(type-name1), NOT NULL and a system required unique index (with a default index name) is generated. This column is referred to as the object identifier column or OID column. The keywords USER GENERATED indicate that the initial value for the OID column must be provided by the user when inserting a row. Once a row is inserted, the OID column cannot be updated (SQLSTATE 42808).

with-options
Defines additional options that apply to columns of a typed table.

column-name
Specifies the name of the column for which additional options are specified. The column-name must correspond to the name of a column of the table that is not also a column of a supertable (SQLSTATE 428DJ). A column name can only appear in one WITH OPTIONS clause in the statement (SQLSTATE 42613).

If an option is already specified as part of the type definition (in CREATE TYPE), the options specified here override the options in CREATE TYPE.

WITH OPTIONS column-options
Defines options for the specified column. See column-options described earlier. If the table is a subtable, primary key or unique constraints cannot be specified (SQLSTATE 429B3).

DATA CAPTURE
Indicates whether extra information for inter-database data replication is to be written to the log. This clause cannot be specified when creating a subtable (SQLSTATE 42613).

If the table is a typed table, then this option is not supported (SQLSTATE 428DH or 42HDR).

NONE
Indicates that no extra information will be logged.

CHANGES
Indicates that extra information regarding SQL changes to this table will be written to the log. This option is required if this table will be replicated and the Capture program is used to capture changes for this table from the log.

If the table is defined to allow data on a partition other than the catalog partition (multiple partition nodegroup or nodegroup with a partition other than the catalog partition), then this option is not supported (SQLSTATE 42997).

If the schema name (implicit or explicit) of the table is longer than 18 bytes, then this option is not supported (SQLSTATE 42997).

Further information about using replication can be found in the Administration Guide and the Replication Guide and Reference.

IN tablespace-name1
Identifies the table space in which the table will be created. The table space must exist, and be a REGULAR table space over which the authorization ID of the statement has USE privilege. If no other table space is specified, then all table parts will be stored in this table space. This clause cannot be specified when creating a subtable (SQLSTATE 42613), since the table space is inherited from the root table of the table hierarchy. If this clause is not specified, a table space for the table is determined as follows:
IF table space IBMDEFAULTGROUP over which the user has USE privilege
  exists with sufficient page size
    THEN choose it
 ELSE IF a table space over which the user has USE privilege 
  exists with sufficient page size
  (see below when multiple table spaces qualify)
    THEN choose it
 ELSE issue an error (SQLSTATE 42727).

If more than one table space is identified by the ELSE IF condition, then choose the table space with the smallest sufficient page size over which the authorization ID of the statement has USE privilege. When more than one table space qualifies, preference is given according to who was granted the USE privilege:

  1. the authorization ID
  2. a group to which the authorization ID belongs
  3. PUBLIC

If more than one table space still qualifies, the final choice is made by the database manager.

Determination of the table space may change when:

  • table spaces are dropped or created
  • USE privileges are granted or revoked.

The sufficient page size of a table is determined by either the byte count of the row or the number of columns. See Row Size for more information.

tablespace-options:
Specifies the table space in which indexes and/or long column values will be stored. See CREATE TABLESPACE for details on types of table spaces.

INDEX IN tablespace-name2
Identifies the table space in which any indexes on the table will be created. This option is allowed only when the primary table space specified in the IN clause is a DMS table space. The specified table space must exist, must be a REGULAR DMS table space over which the authorization ID of the statement has USE privilege, and must be in the same nodegroup as tablespace-name1 (SQLSTATE 42838).

Note that specifying which table space will contain a table's index can only be done when the table is created. The checking of USE privilege over the table space for the index is only carried out at table creation time. The database manager will not require that the authorization ID of a CREATE INDEX statement have USE privilege on the table space when an index is created later.

LONG IN tablespace-name3
Identifies the table space in which the values of any long columns (LONG VARCHAR, LONG VARGRAPHIC, LOB data types, distinct types with any of these as source types, or any columns defined with user-defined structured types with values that cannot be stored inline) will be stored. This option is allowed only when the primary table space specified in the IN clause is a DMS table space. The table space must exist, must be a LONG DMS table space over which the authorization ID of the statement has USE privilege, and must be in the same nodegroup of tablspace-name1 (SQLSTATE 42838).

Note that specifying which table space will contain a table's long and LOB columns can only be done when the table is created. The checking of USE privilege over the table space for the long and LOB columns is only carried out at table creation time. The database manager will not require that the authorization ID of an ALTER TABLE statement have USE privilege on the table space when a long or LOB column is added later.

PARTITIONING KEY (column-name,...)
Specifies the partitioning key used when data in the table is partitioned. Each column-name must identify a column of the table and the same column must not be identified more than once. No column with data type that is a LONG VARCHAR, LONG VARGRAPHIC, BLOB, CLOB, DBCLOB, DATALINK, distinct type based on any of these types, or structured type may be used as part of a partitioning key (SQLSTATE 42962). A partitioning key cannot be specified for a table that is a subtable (SQLSTATE 42613), since the partitioning key is inherited from the root table in the table hierarchy.

If this clause is not specified, and this table resides in a multiple partition nodegroup, then the partitioning key is defined as follows:

  • if the table is a typed table, the object identifier column
  • if a primary key is specified, the first column of the primary key is the partitioning key
  • otherwise, the first column whose data type is not a LOB, LONG VARCHAR, LONG VARGRAPHIC, DATALINK column, distinct type based on one of these types, or structured type column is the partitioning key.

If none of the columns satisfy the requirement of the default partitioning key, the table is created without one. Such tables are allowed only in table spaces defined on single-partition nodegroups.

For tables in table spaces defined on single-partition nodegroups, any collection of non-long type columns can be used to define the partitioning key. If you do not specify this parameter, no partitioning key is created.

For restrictions related to the partitioning key, see Rules.

USING HASHING
Specifies the use of the hashing function as the partitioning method for data distribution. This is the only partitioning method supported.

REPLICATED
Specifies that the data stored in the table is physically replicated on each database partition of the nodegroup of the table space in which the table is defined. This means that a copy of all the data in the table exists on each of these database partitions. This option can only be specified for a summary table (SQLSTATE 42997).

NOT LOGGED INITIALLY
Any changes made to the table by an Insert, Delete, Update, Create Index, Drop Index, or Alter Table operation in the same unit of work in which the table is created are not logged. See Notes for other considerations when using this option.

All catalog changes and storage related information are logged, as are all operations that are done on the table in subsequent units of work.

A foreign key constraint cannot be defined on a table that references a parent with the NOT LOGGED INITIALLY attribute. This clause cannot be specified when creating a subtable (SQLSTATE 42613).
Note:A rollback to savepoint request cannot be issued in the same unit of work as the creation of a NOT LOGGED INITIALLY table. This will result in an error (SQLSTATE 40506), and the entire unit of work will be rolled back.

unique-constraint
Defines a unique or primary key constraint. If the table has a partitioning key, then any unique or primary key must be a superset of the partitioning key. A unique or primary key constraint cannot be specified for a table that is a subtable (SQLSTATE 429B3). If the table is a root table, the constraint applies to the table and all its subtables.

CONSTRAINT constraint-name
Names the primary key or unique constraint. See page ***.

UNIQUE (column-name,...)
Defines a unique key composed of the identified columns. The identified columns must be defined as NOT NULL. Each column-name must identify a column of the table and the same column must not be identified more than once.

The number of identified columns must not exceed 16 and the sum of their stored lengths must not exceed 1024 (refer to Byte Counts for the stored lengths). The length of any individual column must not exceed 255 bytes. This length is for the data only and is not affected by the null byte, should it be present. The maximum data length of a column is 255 bytes, whether the column is nullable or not. No LOB, LONG VARCHAR, LONG VARGRAPHIC, DATALINK, distinct type based on one of these types, or structured type may be used as part of a unique key, even if the length attribute of the column is small enough to fit within the 255 byte limit (SQLSTATE 42962).

The set of columns in the unique key cannot be the same as the set of columns of the primary key or another unique key (SQLSTATE 01543). 81

A unique constraint cannot be specified if the table is a subtable (SQLSTATE 429B3) since unique constraints are inherited from the supertable.

The description of the table as recorded in the catalog includes the unique key and its unique index. A unique index will automatically be created for the columns in the sequence specified with ascending order for each column. The name of the index will be the same as the constraint-name if this does not conflict with an existing index in the schema where the table is created. If the index name conflicts, the name will be SQL, followed by a character timestamp (yymmddhhmmssxxx), with SYSIBM as the schema name.

PRIMARY KEY (column-name,...)
Defines a primary key composed of the identified columns. The clause must not be specified more than once and the identified columns must be defined as NOT NULL. Each column-name must identify a column of the table and the same column must not be identified more than once.

The number of identified columns must not exceed 16 and the sum of their stored lengths must not exceed 1024 (refer to Byte Counts for the stored lengths). The length of any individual column must not exceed 255 bytes. This length is for the data only and is not affected by the null byte, should it be present. The maximum data length of a column is 255 bytes, whether the column is nullable or not. No LOB, LONG VARCHAR, LONG VARGRAPHIC, DATALINK, distinct type based on one of these types, or structured type may be used as part of a primary key, even if the length attribute of the column is small enough to fit within the 255 byte limit (SQLSTATE 42962).

The set of columns in the primary key cannot be the same as the set of columns of a unique key (SQLSTATE 01543). 81

Only one primary key can be defined on a table.

A primary key cannot be specified if the table is a subtable (SQLSTATE 429B3) since the primary key is inherited from the supertable.

The description of the table as recorded in the catalog includes the primary key and its primary index. A unique index will automatically be created for the columns in the sequence specified with ascending order for each column. The name of the index will be the same as the constraint-name if this does not conflict with an existing index in the schema where the table is created. If the index name conflicts, the name will be SQL, followed by a character timestamp (yymmddhhmmssxxx), with SYSIBM as the schema name.

If the table has a partitioning key, the columns of a unique-constraint must be a superset of the partitioning key columns; column order is unimportant.

referential-constraint
Defines a referential constraint.

CONSTRAINT constraint-name
Names the referential constraint. See page ***.

FOREIGN KEY (column-name,...)
Defines a referential constraint with the specified constraint-name.

Let T1 denote the object table of the statement. The foreign key of the referential constraint is composed of the identified columns. Each name in the list of column names must identify a column of T1 and the same column must not be identified more than once. The number of identified columns must not exceed 16 and the sum of their stored lengths must not exceed 1024 (refer to Byte Counts for the stored lengths). No LOB, LONG VARCHAR, LONG VARGRAPHIC, DATALINK, distinct type based on one of these types, or structured type column may be used as part of a foreign key (SQLSTATE 42962). There must be the same number of foreign key columns as there are in the parent key and the data types of the corresponding columns must be compatible (SQLSTATE 42830). Two column descriptions are compatible if they have compatible data types (both columns are numeric, character strings, graphic, date/time, or have the same distinct type).

references-clause
Specifies the parent table and parent key for the referential constraint.

REFERENCES table-name
The table specified in a REFERENCES clause must identify a base table that is described in the catalog, but must not identify a catalog table.

A referential constraint is a duplicate if its foreign key, parent key, and parent table are the same as the foreign key, parent key and parent table of a previously specified referential constraint. Duplicate referential constraints are ignored and a warning is issued (SQLSTATE 01543).

In the following discussion, let T2 denote the identified parent table and let T1 denote the table being created 82 (T1 and T2 may be the same table).

The specified foreign key must have the same number of columns as the parent key of T2 and the description of the nth column of the foreign key must be comparable to the description of the nth column of that parent key. Datetime columns are not considered to be comparable to string columns for the purposes of this rule.

(column-name,...)
The parent key of a referential constraint is composed of the identified columns. Each column-name must be an unqualified name that identifies a column of T2. The same column must not be identified more than once.

The list of column names must match the set of columns (in any order) of the primary key or a unique constraint that exists on T2 (SQLSTATE 42890). If a column name list is not specified, then T2 must have a primary key (SQLSTATE 42888). Omission of the column name list is an implicit specification of the columns of that primary key in the sequence originally specified.

The referential constraint specified by a FOREIGN KEY clause defines a relationship in which T2 is the parent and T1 is the dependent.

rule-clause
Specifies what action to take on dependent tables.

ON DELETE
Specifies what action is to take place on the dependent tables when a row of the parent table is deleted. There are four possible actions:
  • NO ACTION (default)
  • RESTRICT
  • CASCADE
  • SET NULL

The delete rule applies when a row of T2 is the object of a DELETE or propagated delete operation and that row has dependents in T1. Let p denote such a row of T2.

  • If RESTRICT or NO ACTION is specified, an error occurs and no rows are deleted.
  • If CASCADE is specified, the delete operation is propagated to the dependents of p in T1.
  • If SET NULL is specified, each nullable column of the foreign key of each dependent of p in T1 is set to null.

SET NULL must not be specified unless some column of the foreign key allows null values. Omission of the clause is an implicit specification of ON DELETE NO ACTION.

A cycle involving two or more tables must not cause a table to be delete-connected to itself unless all of the delete rules in the cycle are CASCADE. Thus, if the new relationship would form a cycle and T2 is already delete connected to T1, then the constraint can only be defined if it has a delete rule of CASCADE and all other delete rules of the cycle are CASCADE.

If T1 is delete-connected to T2 through multiple paths, those relationships in which T1 is a dependent and which form all or part of those paths must have the same delete rule and it must not be SET NULL. The NO ACTION and RESTRICT actions are treated identically. Thus, if T1 is a dependent of T3 in a relationship with a delete rule of r, the referential constraint cannot be defined when r is SET NULL if any of these conditions exist:

  • T2 and T3 are the same table
  • T2 is a descendant of T3 and the deletion of rows from T3 cascades to T2
  • T3 is a descendant of T2 and the deletion of rows from T2 cascades to T3
  • T2 and T3 are both descendants of the same table and the deletion of rows from that table cascades to both T2 and T3.

If r is other than SET NULL, the referential constraint can be defined, but the delete rule that is implicitly or explicitly specified in the FOREIGN KEY clause must be the same as r.

In applying the above rules to referential constraints, in which either the parent table or the dependent table is a member of a typed table hierarchy, all the referential constraints that apply to any table in the respective hierarchies are taken into consideration.

ON UPDATE
Specifies what action is to take place on the dependent tables when a row of the parent table is updated. The clause is optional. ON UPDATE NO ACTION is the default and ON UPDATE RESTRICT is the only alternative.

The difference between NO ACTION and RESTRICT is described under CREATE TABLE in Notes.

check-constraint
Defines a check constraint. A check-constraint is a search-condition that must evaluate to not false.

CONSTRAINT constraint-name
Names the check constraint. See page ***.

CHECK (check-condition)
Defines a check constraint. A check-condition is a search-condition except as follows:
  • A column reference must be to a column of the table being created
  • The search-condition cannot contain a TYPE predicate
  • It cannot contain any of the following (SQLSTATE 42621):
    • subqueries
    • dereference operations or DEREF functions where the scoped reference argument is other than the object identifier (OID) column.
    • CAST specifications with a SCOPE clause
    • column functions
    • functions that are not deterministic
    • functions defined to have an external action
    • user-defined functions using the SCRATCHPAD option
    • user-defined functions using the READS SQL DATA option
    • host variables
    • parameter markers
    • special registers
    • an alias
    • references to generated columns other than the identity column

If a check constraint is specified as part of a column-definition then a column reference can only be made to the same column. Check constraints specified as part of a table definition can have column references identifying columns previously defined in the CREATE TABLE statement. Check constraints are not checked for inconsistencies, duplicate conditions or equivalent conditions. Therefore, contradictory or redundant check constraints can be defined resulting in possible errors at execution time.

The check-condition "IS NOT NULL" can be specified, however it is recommended that nullability be enforced directly using the NOT NULL attribute of a column. For example, CHECK (salary + bonus > 30000) is accepted if salary is set to NULL, because CHECK constraints must be either satisfied or unknown and in this case salary is unknown. However, CHECK (salary IS NOT NULL) would be considered false and a violation of the constraint if salary is set to NULL.

Check constraints are enforced when rows in the table are inserted or updated. A check constraint defined on a table automatically applies to all subtables of that table.

Rules

The following rules only apply to partitioned databases.

Notes

Examples

Example 1:  Create table TDEPT in the DEPARTX table space. DEPTNO, DEPTNAME, MGRNO, and ADMRDEPT are column names. CHAR means the column will contain character data. NOT NULL means that the column cannot contain a null value. VARCHAR means the column will contain varying-length character data. The primary key consists of the column DEPTNO.

   CREATE TABLE TDEPT
     (DEPTNO   CHAR(3)     NOT NULL,
      DEPTNAME VARCHAR(36) NOT NULL,
      MGRNO    CHAR(6),
      ADMRDEPT CHAR(3)     NOT NULL,
      PRIMARY KEY(DEPTNO))
   IN DEPARTX

Example 2:  Create table PROJ in the SCHED table space. PROJNO, PROJNAME, DEPTNO, RESPEMP, PRSTAFF, PRSTDATE, PRENDATE, and MAJPROJ are column names. CHAR means the column will contain character data. DECIMAL means the column will contain packed decimal data. 5,2 means the following: 5 indicates the number of decimal digits, and 2 indicates the number of digits to the right of the decimal point. NOT NULL means that the column cannot contain a null value. VARCHAR means the column will contain varying-length character data. DATE means the column will contain date information in a three-part format (year, month, and day).

   CREATE TABLE PROJ
     (PROJNO   CHAR(6)      NOT NULL,
      PROJNAME VARCHAR(24)  NOT NULL,
      DEPTNO   CHAR(3)      NOT NULL,
      RESPEMP  CHAR(6)      NOT NULL,
      PRSTAFF  DECIMAL(5,2)         ,
      PRSTDATE DATE                 ,
      PRENDATE DATE                 ,
      MAJPROJ  CHAR(6)      NOT NULL)
   IN SCHED

Example 3:  Create a table called EMPLOYEE_SALARY where any unknown salary is considered 0. No table space is specified, so that the table will be created in a table space selected by the system based on the rules descirbed for the IN tablespace-name1 clause.

   CREATE TABLE EMPLOYEE_SALARY
     (DEPTNO   CHAR(3)      NOT NULL,
      DEPTNAME VARCHAR(36)  NOT NULL,
      EMPNO    CHAR(6)      NOT NULL,
      SALARY   DECIMAL(9,2) NOT NULL WITH DEFAULT)

Example 4:  Create distinct types for total salary and miles and use them for columns of a table created in the default table space. In a dynamic SQL statement assume the CURRENT SCHEMA special register is JOHNDOE and the CURRENT PATH is the default ("SYSIBM","SYSFUN","JOHNDOE").

If a value for SALARY is not specified it must be set to 0 and if a value for LIVING_DIST is not specified it must to set to 1 mile.

  CREATE DISTINCT TYPE JOHNDOE.T_SALARY AS INTEGER WITH COMPARISONS
 
  CREATE DISTINCT TYPE JOHNDOE.MILES AS FLOAT WITH COMPARISONS
 
  CREATE TABLE EMPLOYEE
     (ID          INTEGER NOT NULL,
      NAME        CHAR (30),
      SALARY      T_SALARY NOT NULL WITH DEFAULT,
      LIVING_DIST MILES    DEFAULT MILES(1) )

Example 5:  Create distinct types for image and audio and use them for columns of a table. No table space is specified, so that the table will be created in a table space selected by the system based on the rules descirbed for the IN tablespace-name1 clause. Assume the CURRENT PATH is the default.

  CREATE DISTINCT TYPE IMAGE AS BLOB (10M)
 
  CREATE DISTINCT TYPE AUDIO AS BLOB (1G)
 
  CREATE TABLE PERSON
     (SSN    INTEGER NOT NULL,
      NAME   CHAR (30),
      VOICE  AUDIO,
      PHOTO  IMAGE)

Example 6:  Create table EMPLOYEE in the HUMRES table space. The constraints defined on the table are the following:

Note:If the columns included in the check constraints are nullable they could also be NULL.
   CREATE TABLE EMPLOYEE
   (ID          SMALLINT NOT NULL,
    NAME        VARCHAR(9),
    DEPT        SMALLINT CHECK (DEPT BETWEEN 10 AND 100),
    JOB         CHAR(5) CHECK (JOB IN ('Sales','Mgr','Clerk')),
    HIREDATE    DATE,
    SALARY      DECIMAL(7,2),
    COMM        DECIMAL(7,2),
    PRIMARY KEY (ID),
    CONSTRAINT  YEARSAL CHECK (YEAR(HIREDATE) > 1986 OR SALARY > 40500)
   )
   IN HUMRES

Example 7:  Create a table that is wholly contained in the PAYROLL table space.

   CREATE TABLE EMPLOYEE .....
      IN PAYROLL

Example 8:  Create a table with its data part in ACCOUNTING and its index part in ACCOUNT_IDX.

   CREATE TABLE SALARY.....
      IN ACCOUNTING INDEX IN ACCOUNT_IDX

Example 9:  Create a table and log SQL changes in the default format.

   CREATE TABLE SALARY1 .....

or

   CREATE TABLE SALARY1 .....
      DATA CAPTURE NONE

Example 10:  Create a table and log SQL changes in an expanded format.

   CREATE TABLE SALARY2 .....
      DATA CAPTURE CHANGES

Example 11:  Create a table EMP_ACT in the SCHED table space. EMPNO, PROJNO, ACTNO, EMPTIME, EMSTDATE, and EMENDATE are column names. Constraints defined on the table are:

   CREATE TABLE EMP_ACT
   (EMPNO       CHAR(6) NOT NULL,
    PROJNO      CHAR(6) NOT NULL,
    ACTNO       SMALLINT NOT NULL,
    EMPTIME     DECIMAL(5,2),
    EMSTDATE    DATE,
    EMENDATE    DATE,
    CONSTRAINT EMP_ACT_UNIQ UNIQUE (EMPNO,PROJNO,ACTNO),
    CONSTRAINT FK_ACT_PROJ FOREIGN KEY (PROJNO)
                           REFERENCES PROJECT (PROJNO) ON DELETE CASCADE
   )
   IN SCHED

A unique index called EMP_ACT_UNIQ is automatically created in the same schema to enforce the unique constraint.

Example 12:  Create a table that is to hold information about famous goals for the ice hockey hall of fame. The table will list information about the player who scored the goal, the goaltender against who it was scored, the date and place, and a description. When available, it will also point to places where newspaper articles about the game are stored and where still and moving pictures of the goal are stored. The newspaper articles are to be linked so they cannot be deleted or renamed but all existing display and update applications must continue to operate. The still pictures and movies are to be linked with access under complete control of DB2. The still pictures are to have recovery and are to be returned to their original owner if unlinked. The movie pictures are not to have recovery and are to be deleted if unlinked. The description column and the three DATALINK columns are nullable.

  CREATE TABLE HOCKEY_GOALS
    ( BY_PLAYER      VARCHAR(30)   NOT NULL,
      BY_TEAM        VARCHAR(30)   NOT NULL,
      AGAINST_PLAYER VARCHAR(30)   NOT NULL,
      AGAINST_TEAM   VARCHAR(30)   NOT NULL,
      DATE_OF_GOAL   DATE          NOT NULL,
      DESCRIPTION    CLOB(5000),
      ARTICLES       DATALINK  LINKTYPE URL FILE LINK CONTROL MODE DB2OPTIONS,
      SNAPSHOT       DATALINK  LINKTYPE URL FILE LINK CONTROL
                               INTEGRITY ALL
                               READ PERMISSION DB WRITE PERMISSION BLOCKED
                               RECOVERY YES ON UNLINK RESTORE,
      MOVIE          DATALINK  LINKTYPE URL FILE LINK CONTROL
                               INTEGRITY ALL
                               READ PERMISSION DB WRITE PERMISSION BLOCKED
                               RECOVERY NO ON UNLINK DELETE )

Example 13:  Suppose an exception table is needed for the EMPLOYEE table. One can be created using the following statement.

  CREATE TABLE EXCEPTION_EMPLOYEE AS
    (SELECT EMPLOYEE.*, 
       CURRENT TIMESTAMP AS TIMESTAMP,
       CAST ('' AS CLOB(32K)) AS MSG
     FROM EMPLOYEE
     ) DEFINITION ONLY
				     

Example 14:  Given the following table spaces with the indicated attributes:

   TBSPACE            PAGESIZE    USER   USERAUTH
   ------------------ ----------- ------ --------
   DEPT4K                    4096 BOBBY  Y
   PUBLIC4K                  4096 PUBLIC Y
   DEPT8K                    8192 BOBBY  Y
   DEPT8K                    8192 RICK   Y
   PUBLIC8K                  8192 PUBLIC Y

Example 15:  Create a table with a LEAD column defined with the structured type EMP. Specify an INLINE LENGTH of 300 bytes for the LEAD column, indicating that any instances of LEAD that cannot fit within the 300 bytes are stored outside the table (separately from the base table row, similar to the way LOB values are handled).

  CREATE TABLE PROJECTS (PID INTEGER, 
    LEAD EMP INLINE LENGTH 300,
    STARTDATE DATE,
              ...)

Example 16:  Create a table DEPT with five columns named DEPTNO, DEPTNAME, MGRNO, ADMRDEPT, and LOCATION. Column DEPT is to be defined as an IDENTITY column such that DB2 will always generate a value for it. The values for the DEPT column should begin with 500 and increment by 1.

  CREATE TABLE DEPT
     (DEPTNO SMALLINT NOT NULL
        GENERATED ALWAYS AS IDENTITY
        (START WITH 500, INCREMENT BY 1),
      DEPTNAME VARCHAR (36) NOT NULL,
      MGRNO CHAR(6),
      ADMRDEPT SMALLINT NOT NULL,
      LOCATION CHAR(30))


Footnotes:

74
Observe that it is not possible to specify the FOR BIT DATA clause for CLOB columns. However, a CHAR FOR BIT DATA string can be assigned to a CLOB column and a CHAR FOR BIT DATA string can be concatenated with a CLOB string.

75
With DB2 Universal Database, the file is assigned to a special predefined "dfmunknown" user id.

76
The identifier is formed of "SQL" followed by a sequence of 15 numeric characters generated by a timestamp-based function.

77
Identity columns are not be supported in a database with multiple partitions (SQLSTATE 42997). An identity column cannot be created if more than one partition for the database exists. A database that includes any identity columns cannot be started with more than one partition.

78
SMALLINT, INTEGER, BIGINT, or DECIMAL with a scale of zero, or a distinct type based on one of these types are considered exact numeric types. By contrast, single and double precision floating points are considered approximate numeric data types. Reference types, even if represented by an exact numeric type cannot be defined as identity columns.

79
If a database is not explicitly activated (using the ACTIVATE command or API), when the last application is disconnected from the database, an implicit deactivation occurs.

80
If the expression for a GENERATED ALWAYS column includes a user-defined external function, changing the executable for the function (such that the results change for given arguments) can result in inconsistent data. This can be avoided by using the SET INTEGRITY statement to force the generation of new values.

81
If LANGLEVEL is SQL92E or MIA then an error is returned, SQLSTATE 42891.

82
or altered, in the case where this clause is referenced from the description of the ALTER TABLE statement.


[ Top of Page | Previous Page | Next Page ]