Link to home
Start Free TrialLog in
Avatar of BILL Carlisle
BILL CarlisleFlag for United States of America

asked on

How would I write a Constraint to ensure that there is only one record that is active for any one templ_id.

Hi, How would I write a Constraint to ensure that there is only one record that is active for any one templ_id.

This is valid... but two actives ones would not be valid.
templ_id       status
 1                 inactive
 1                 active
 1                 inactive



ALTER TABLE employee
    ADD CONSTRAINT unq_templ_id_active_status_ck
    CHECK (??????????????? );
SOLUTION
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Check constraint do NOT span more than one record. What you need is a unique function index:

create unique index emp_active_uk on employee (decode(status,'active',templ_id,null),decode(status,'active','active',null))
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

>>What you need is a unique function index:

Very nice!!!

Yes, go with that.  It's better than my trigger suggestion.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Forgot to mention: the problem with triggers is concurrency. If two people simultaneously try to INSERT the same ID with 'active' status, the only way you can enforce uniqueness is having an autonomous transaction insert the ID into an auxiliary structure and fail if there's a duplicate. In effect, you'd be implementing the unique index anyway...
>>If two people simultaneously try to INSERT

I stand corrected again.  ;)
Avatar of BILL Carlisle

ASKER

That Unique constraint worked awesome! Thanks!