How to implement an auto-increment field in Db2?
In Db2, you can achieve automatic incrementing fields by using the IDENTITY column attribute. This attribute can be specified when creating a table to automatically generate unique incrementing values for that column. The specific steps are as follows:
- When creating a table, specify the IDENTITY column property on fields that require automatic incrementation, for example:
CREATE TABLE example_table (
id INTEGER GENERATED ALWAYS AS IDENTITY,
name VARCHAR(50)
);
In the above example, the id field is set as an auto-increment field, so a unique value will be automatically generated and incremented each time data is inserted.
- When inserting data, there is no need to specify the value of the auto-increment fields, Db2 will automatically generate an increasing value for that field, for example:
INSERT INTO example_table (name) VALUES ('John');
In the example above, the value of the id field will be automatically generated and inserted into the table.
By following the above steps, you can achieve automatic incremental field in Db2.