Creating and altering an identity column

Every time a row is added to a table with an identity column, the identity column value for the new row is generated by the system.

Only columns of type SMALLINT, INTEGER, BIGINT, DECIMAL, or NUMERIC can be created as identity columns. You are allowed only one identity column per table. When you are changing a table definition, only a column that you are adding can be specified as an identity column; existing columns cannot.

When you create a table, you can define a column in the table to be an identity column. For example, create a table ORDERS with three columns called ORDERNO, SHIPPED_TO, and ORDER_DATE. Define ORDERNO as an identity column.

CREATE TABLE ORDERS
   (ORDERNO SMALLINT NOT NULL
   GENERATED ALWAYS AS IDENTITY
   (START WITH 500 
   INCREMENT BY 1 
   CYCLE),
   SHIPPED_TO VARCHAR (36) ,
   ORDER_DATE DATE)

This column is defined with a starting value of 500, incremented by 1 for every new row inserted, and will recycle when the maximum value is reached. In this example, the maximum value for the identity column is the maximum value for the data type. Because the data type is defined as SMALLINT, the range of values that can be assigned to ORDERNO is from 500 to 32 767. When this column value reaches 32 767, it will restart at 500 again. If 500 is still assigned to a column, and a unique key is specified on the identity column, a duplicate key error is returned. The next insert operation will attempt to use 501. If you do not have a unique key specified for the identity column, 500 is used again, regardless of how many times it appears in the table.

For a larger range of values, specify the column to be data type INTEGER or even BIGINT. If you want the value of the identity column to decrease, specify a negative value for the INCREMENT option. It is also possible to specify the exact range of numbers by using MINVALUE and MAXVALUE.

You can modify the attributes of an existing identity column using the ALTER TABLE statement. For example, you want to restart the identity column with a new value:

ALTER TABLE ORDER         
  ALTER COLUMN ORDERNO         
  RESTART WITH 1

You can also drop the identity attribute from a column:

ALTER TABLE ORDER         
  ALTER COLUMN ORDERNO        
  DROP IDENTITY

The column ORDERNO remains as a SMALLINT column, but the identity attribute is dropped. The system will no longer generate values for this column.