I was trying to enforce only one active phone per client using a unique index in Oracle but can't make it work. This works flawlessly in PostgreSQL and DB2 but doesn't seem to work in Oracle.
Here's the example:
create table phone (
client_id number(6) not null,
active number(1) not null check (active in (0, 1)),
value varchar2(15)
);
insert into phone (client_id, active, value) values (10, 0, '1111');
insert into phone (client_id, active, value) values (10, 1, '3333');
insert into phone (client_id, active, value) values (15, 0, '5555');
insert into phone (client_id, active, value) values (15, 1, '6666');
insert into phone (client_id, active, value) values (15, 0, '7777'); -- offending row
When I try to create the index:
create unique index ix1 on phone (client_id, case when active = 1 then active end);
It seems that Oracle doesn't like it because a duplicate index entry:
Error: ORA-01452: cannot CREATE UNIQUE INDEX; duplicate keys found
SQLState: 72000
If I remove the offending data row, the index can be created.
case
with noelse
. Is Oracle assigned a 0 to the result of thecase
when it's not 1? It seems that when the row isn't active, it'll be0
, resulting in two rows with a (15, 0). The title of your question asks about NULL, but I don't see NULL coming into the equation here(?).on phone (case when active=1 then client_id end)
to work across database engines. I don't have time to verify that and write up an answer right now but will try to do so later if no one beats me to it.else
value isnull
(not only in Oracle but, I believe, in the SQL Standard). So the OP's attempt was fine from that point of view. The issue was different - it's what MT0 explained in his answer.null
is never equal tonull
.