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

后端 未结 2 531
误落风尘
误落风尘 2021-02-04 12:44

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)
<         


        
2条回答
  •  猫巷女王i
    2021-02-04 13:06

    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);
    

提交回复
热议问题