6

I have the following unique constraint

dup_Checklist_QNum UNIQUE (QUESTION_NO, IS_ACTIVE)

I am trying to prevent two questions having the same question number while being active (IS_ACTIVE value = 1).

All seemed fine until I had to rev a question for the second time.

QUESTION_NO=1, TEXT="Have you..", REV=1, IS_ACTIVE=0  
QUESTION_NO=1, TEXT="Have you..", REV=2, IS_ACTIVE=0  <-- This should be ok but constraint was violated
QUESTION_NO=1, TEXT="Have you..", REV=3, IS_ACTIVE=1
QUESTION_NO=1, TEXT="Have you..", REV=3, IS_ACTIVE=1 <-- This should be throw constraint exception 

I need the constraint to only apply when IS_ACTIVE=1

2
  • I guess as a work around, I could just deactivate questions by using a unique number, 0.1, 0.2, 0.3, etc... Provided my application only cares when the value is 1, and ignores all other questions. Commented Jul 4, 2012 at 22:15
  • 2
    possible duplicate of Conditional unique constraint in oracle db Commented Jul 4, 2012 at 22:22

2 Answers 2

18

You can create a unique function-based index

CREATE UNIQUE INDEX idx_dup_active
    ON <<table name>>( CASE WHEN is_active = 1
                            THEN question_no
                            ELSE NULL
                        END );

This takes advantage of the fact that Oracle b-tree indexes do not store data where the leaf block data would be entirely NULL.

Sign up to request clarification or add additional context in comments.

2 Comments

I wonder when Oracle finally gives us less clumsy partial indexes by allowing a WHERE clause for the CREATE INDEX.
I have a similar case but the unique constraint needs to be on 2 columns, I'm trying to wrap my head around the syntax
0

For multiple columns, you can create unique index using the following syntax:

CREATE UNIQUE INDEX idx_dup_active
    ON <<table name>>( CASE WHEN is_active = 1
                            THEN question_no||IS_ACTIVE
                            ELSE NULL
                        END );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.