Oracle SQL Constraint where clause
-
29-06-2021 - |
Question
I have the table Tester on oracle with the following columns:
- TesterID
- TesterName
- IsDefault
- Application_ID
TesterID is the primary key. Now I want that there can only be one Default Tester, which means only one Tester can have the calues IsDefault =Y at an ApplicationID.
I tried it with a constraint:
alter table Tester add constraint Tester_ISDEFAULT UNIQUE(IsDefault,Application_ID);
Is it possible to make the unique key on where isdefault= Y?
Thanks for help!
La solution
Not with a UNIQUE
constraint. However, you can use a UNIQUE INDEX
instead:
CREATE UNIQUE INDEX ApplicationId_Default_Y ON tester (
CASE WHEN IsDefault = 'Y'
THEN ApplicationId
ELSE NULL
END
);
Here's a DEMO.
Autres conseils
You can do this with a function-based unique index, not a constraint as such:
create unique index tester_isdefault on tester
(case when isdefault='Y' then application_id end);
Since Oracle doesn't created index entries for keys that are all null, only rows where isdefault='Y' will appear in the index.
That constraint won't work as it would mean you can only have two rows for each Application_ID - one with IsDefault=0 and the other with IsDefault=1.
You could enforce this logic with a trigger. Or, why not just enforce it in your application logic?
create unique index tester_ui_1 on tester(decode(is_default, 'Y', 0, tester_id), application_id)