How can I create a unique index in Oracle but ignore nulls?

二次信任 提交于 2019-12-03 23:21:10

问题


I am trying to create a unique constraint on two fields in a table. However, there is a high likelihood that one will be null. I only require that they be unique if both are not null (name will never be null).

create unique index "name_and_email" on user(name, email);

Ignore the semantics of the table and field names and whether that makes sense - I just made some up.

Is there a way to create a unique constraint on these fields that will enforce uniqueness for two not null values, but ignore if there are multiple entries where name is not null and email is null?

This question is for SQL Server, and I'm hoping that the answer is not the same: How do I create a unique constraint that also allows nulls?


回答1:


We can do this with a function-based index. The following makes use of NVL2() which, as you know, returns one value if the expression is not null and a different value if it is null. You could use CASE() instead.

SQL> create table blah (name varchar2(10), email varchar2(20))
  2  /

Table created.

SQL> create unique index blah_uidx on blah
  2      (nvl2(email, name, null), nvl2(name, email, null))
  3  /

Index created.

SQL> insert into blah values ('APC', null)
  2  /

1 row created.

SQL> insert into blah values ('APC', null)
  2  /

1 row created.

SQL> insert into blah values (null, 'apc@example.com')
  2  /

1 row created.

SQL> insert into blah values (null, 'apc@example.com')
  2  /

1 row created.

SQL> insert into blah values ('APC', 'apc@example.com')
  2  /

1 row created.

SQL> insert into blah values ('APC', 'apc@example.com')
  2  /
insert into blah values ('APC', 'apc@example.com')
*
ERROR at line 1:
ORA-00001: unique constraint (APC.BLAH_UIDX) violated


SQL>

Edit

Because in your scenario name will always be populated you will only need an index like this:

SQL> create unique index blah_uidx on blah
  2      (nvl2(email, name, null), email)
  3  /

Index created.

SQL> 



回答2:


I don't know how many people still get directed to this answer, but at least in the latest version of oracle, you're allowed to have multiple rows with null on a unique index and the accepted answer isn't necessary



来源:https://stackoverflow.com/questions/1374737/how-can-i-create-a-unique-index-in-oracle-but-ignore-nulls

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!