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

21,549

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);
Share:
21,549
Eric
Author by

Eric

Updated on October 28, 2020

Comments

  • Eric
    Eric over 3 years

    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?

  • Vadzim
    Vadzim about 9 years
    This doesn't address uniqueness requirement. Several nulls would clash.