Search code examples
oracle-databaseconstraintssequenceoracle12cddl

Oracle constraint within a sequence


I'm trying to create a constraint on a column that it must be within a sequence (i.e. col_name < seq.maxval)

I tried to use a regular constraint, but the column doesn't have anything to tie to - it is just a sequence, not a column in a table.

Checks can't reference any kind of query, so I don't think that would work either.

ALTER TABLE STE_FILECOLL ADD (
  CONSTRAINT STE_FC_CLFC_REF_STEF_IDFILE
  FOREIGN KEY (CLFILECOLL) 
  REFERENCES ????
  ENABLE VALIDATE
);

I expect there is a way to make sure that the values of a column are within a sequence, but an hour of reading documentation and duckduckgoing have been fruitless, so I turn to here.


Solution

  • In Oracle DB version 12c, a sequence's next value might be set as default for a column :

    create table STE_FILECOLL
    (
      col0     int default seq1.nextval not null,
      col_name int
    );
    

    and then check constraints might be added to provide the desired condition as :

    alter table STE_FILECOLL
      add constraint STE_CC_CLFC_REF_STEF_IDFILE
      check (col_name < col0);