Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional unique constraint in oracle db

I have a situation where I need to enforce a unique constraint on a column[attribute] depending on another column value.

So for example, I have a table like Table(ID, EID, Name, ISDeleted)

ISDeleted can only have a value null or 'y' (active or deleted), and i want to create a unique constraint on EID, ISDeleted only when ISDeleted = null, since I dont care if there are multiple deleted records with the same id. Please note that, EID can have null value.

I am using Oracle DB for this.

like image 671
D3V Avatar asked Apr 25 '12 14:04

D3V


People also ask

How do you enforce conditional unique multiple columns?

We implement this using CASE WHEN ensconced in the CREATE UNIQUE INDEX statement: SQL> -- Conditional unique index on multiple columns SQL> create unique index demo_fbi_idx 2 on demo_fbi 3 (case when active_flag = 'Y' then 4 col1 else null end, 5 case when active_flag = 'Y' then 6 col2 else null end); Index created.

What is unique constraint in Oracle?

Unique Constraints. Unique constraints ensure that the data in a column or combination of columns is unique for each row. A table's primary key, for example, functions as an implicit unique constraint.

How do you create a composite unique constraint in Oracle?

The syntax for creating a unique constraint using an ALTER TABLE statement in Oracle is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.


1 Answers

You can't create a constraint. But you can create a unique function-based index. This takes advantage of the fact that Oracle does not index NULL values-- any rows where isDeleted is NOT NULL will not be included in the index so the unique constraint won't apply to them.

CREATE UNIQUE INDEX one_not_deleted
    ON table_name( (CASE WHEN isDeleted IS NULL
                         THEN eid
                         ELSE null
                      END) );
like image 90
Justin Cave Avatar answered Oct 19 '22 12:10

Justin Cave