Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create unique index on fields with possible null values (Oracle 11g)?

Here is the sample table with 3 columns (ID, UNIQUE_VALUE, UNIQUE_GROUP_ID)

I want below records can be allowed:

(1, NULL, NULL)
(2, NULL, NULL)

or

(3, NULL, 7)
(4, 123, 7)

or (Note: this condition is not allowed in unique index nor unique constraint)

(5, NULL, 7)
(6, NULL, 7)

and these can't be allowed:

(7, 123, 7)
(8, 123, 7)

I created a unique index on last 2 columns, but only the first 2 examples can be allowed.

Is it possible to let db check the uniqueness of these 2 columns only when both are not null?

like image 848
Eric Avatar asked Oct 24 '12 04:10

Eric


People also ask

Can unique index have NULL values in Oracle?

Hence, Oracle indexes will not include NULL values.

Can unique index have NULL values?

Therefore, unique indexes do not enforce primary key constraints by themselves because they allow null values.

Can we create unique index on NULLable column in Oracle?

To make a local unique index, one of its columns must be the partition key. Without a function on it! To allow multiple nulls you need to add something to make the index entries unique when oracle_id is null.

Can unique index have NULL values SQL?

Unique fields in SQL Server are created using unique constraints or unique indexes, furthermore, each unique constraint uses a unique index. Regardless of using unique constraint or unique index, the field can accept null values, however the uniqueness will result in only accepting a single row with null value.


1 Answers

You want to only enforce uniqueness on the rows where both UNIQUE_VALUE and UNIQUE_GROUP_ID are not null. To do this, you can use a unique function-based index:

CREATE UNIQUE INDEX func_based_index ON the_table
  (CASE WHEN unique_value IS NOT NULL
         AND unique_group_id IS NOT NULL
        THEN UNIQUE_VALUE || ',' || UNIQUE_GROUP_ID
   END);
like image 76
Jeffrey Kemp Avatar answered Oct 12 '22 16:10

Jeffrey Kemp