0

Consider that there is the following table:

create table table_1(
    id                 serial
                       PRIMARY KEY,
    col1               varchar(50),
    col2               varchar(50),
    status             varchar(1)  -- A=active P=pending D=Deleted
);

now what I want is to create a unique constraint on (col1,col2) but it should not consider those with status ='D' i.e Consider there is 2 rows in the table:

INSERT INTO table_1(col1,col2,status) VALUES ('row1', 'row1', 'A');
INSERT INTO table_1(col1,col2,status) VALUES ('row2', 'row2', 'D');

Then I should NOT be able to add the following row:

INSERT INTO table_1(col1,col2,status) VALUES ('row1', 'row1', 'A');

But I SHOULD be able to add the following row:

INSERT INTO table_1(col1,col2,status) VALUES ('row2', 'row2', 'A');

1 Answer 1

1

You can do this with a partial unique index:

create unique index id_table1_col1_col2_status on table_1(col1, col2, status)
    where status <> 'D';

Here is a SQL Fiddle that you can use to see it work.

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

2 Comments

Thank you. I just need this: create unique index id_table1_col1_col2 on table_1(col1, col2) where status <> 'D'; I did not know we could use WHERE when creating an index.
How will status <> 'D' work if status is null? If it's never going to be null, then it should be created with the not null constraint.

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.