Skip to content
Advertisement

Unique value Constraint with multiple columns across the table, not the combination in Oracle

In oracle is there a way to enforce uniqueness among two columns?

Its not the uniqueness among combination of two columns, but values across table among two columns.

References:

Unique value constraint across multiple columns

Example data, which should not be allowed:

Unique constraint on combination of two columns?

My Oracle Version:

Advertisement

Answer

I would use a check() constraint to ensure unicity on each row, and a unique index for unicity across rows:

The upside of this approach is that it also prevents inserts of tuples like (111, 222) and (222, 111).

Demo on DB Fiddle:

ORA-02290: check constraint (FIDDLE_SMBYKTEIHNNVOHKZSCYK.SYS_C0020876) violated
ORA-00001: unique constraint (FIDDLE_SMBYKTEIHNNVOHKZSCYK.MYIDX) violated
ORA-06512: at line 3
ORA-00001: unique constraint (FIDDLE_SMBYKTEIHNNVOHKZSCYK.MYIDX) violated
ORA-06512: at line 3
ORA-00001: unique constraint (FIDDLE_SMBYKTEIHNNVOHKZSCYK.MYIDX) violated
ORA-06512: at line 3
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement