The easiest way to create an auto-increment field in a Firebird database

Is there an easy way to create an auto growth field using Firebird? I installed the FlameRobin administration tool, but the process of creating an auto-increment field using the tool is complicated. Can I create such an identification field simply by clicking a check box or using a tool other than Flamerobin?

+6
source share
1 answer

Firebird 2.5 and earlier do not have auto-increment fields. You need to create them yourself using a sequence (aka generator) and a trigger.

Sequence is the standard SQL term, and generator is the historical Firebird term, both of which are used.

In create sequence :

CREATE SEQUENCE t1_id_sequence; 

To create a trigger to always generate an identifier in table T1 using the primary key ID :

 set term !! ; CREATE TRIGGER T1_AUTOINCREMENT FOR T1 ACTIVE BEFORE INSERT POSITION 0 AS BEGIN NEW.ID = next value for t1_id_sequence; END!! set term ; !! 

See also: How to create an auto-increment column?

Firebird 3 makes this a little easier as it introduces identifier columns. In practice, this is syntactic sugar to create a sequence + trigger for you.

for instance

 create table t1 ( id integer generated by default as identity primary key ) 

Firebird 3 only supports " generated by default ", which means that users can specify their own id values ​​(which can lead to duplicate value errors); " generated always " will be added by Firebird 4.

See also Firebird 3 release notes , "Identifier Column Type" section.

Flamerobin also provides sequence + trigger tools for you. If you have an existing table, you can do the following:

  • Open the table properties:

    open table properties

  • Open the column properties in the primary key column

    open column properties

  • Default column properties, select a new generator and create a trigger:

    default column properties

  • A generator (sequence) and a startup code generated by a flamerobin. Please note that contrary to my example above, this trigger allows the user to specify their id value, with some logic, to avoid duplication in the future. Do this (and don't forget to commit):

    generated code for generator + trigger

+17
source

All Articles