Auto numbering and identifier columns
An identity column provides a way for Db2® to automatically generate a unique numeric value for each row that is added to the table.
When creating a table in which you must uniquely identify each row that will be added to the table, you can add an identity column to the table. To guarantee a unique numeric value for each row that is added to a table, you should define a unique index on the identity column or declare it a primary key.
Other uses of an identity column are an order number, an employee number, a stock number, or an incident number. The values for an identity column can be generated by the Db2 database manager: ALWAYS or BY DEFAULT.
An identity column defined as GENERATED ALWAYS is given values that are always generated by the Db2 database manager. Applications are not allowed to provide an explicit value. An identity column defined as GENERATED BY DEFAULT gives applications a way to explicitly provide a value for the identity column. If the application does not provide a value, then Db2 will generate one. Since the application controls the value, Db2 cannot guarantee the uniqueness of the value. The GENERATED BY DEFAULT clause is meant for use for data propagation where the intent is to copy the contents of an existing table; or, for the unload and reloading of a table.
Once created, you first have to add the column with the DEFAULT option to get the existing default value. Then you can ALTER the default to become an identity column.
If rows are inserted into a table with explicit identity column values specified, the next internally generated value is not updated, and might conflict with existing values in the table. Duplicate values will generate an error message if the uniqueness of the values in the identity column is being enforced by a primary-key or a unique index that has been defined on the identity column.
To define an identity column on a new table, use the AS IDENTITY clause on the CREATE TABLE statement.
Example
CREATE TABLE table (col1 INT,
col2 DOUBLE,
col3 INT NOT NULL GENERATED ALWAYS AS IDENTITY
(START WITH 100, INCREMENT BY 5))
In
this example the third column is the identity column. You can also
specify the value used in the column to uniquely identify each row
when added. Here the first row entered has the value of 100
placed
in the column; every subsequent row added to the table has the associated
value increased by five.