0

On PostgreSQL, I have a table with the columns name, surname and _deleted.

name and surname cannot be duplicated, so I had a unique constraint on them and everything was good.

after that, I added the _deleted for soft deletes. If I add (name, surname) and then I soft delete it, I cannot add anymore (name, surname).

I thought that the solution was adding unique to (name, surname, _deleted) but it does not work, because _deleted is a DateTime that is null when it is not deleted, hence NULL can be multiple.

How can I add a proper constraint?

2 Answers 2

2

You want a filtered unique index:

create unique index unq_t_name_surname
    on t(name, surname)
    where _deleted is not null;

You cannot (easily) do this with a unique constraint, but this is functionally equivalent to a constraint.

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

3 Comments

Does it change the update performance? I do not know how the constraints are checked, but adding an index would change the update performance and occupies size on disk. However it works, than you!
@EuberDeveloper . . . The performance is pretty much the same. Unique constraints are implemented using unique indexes. The filtering on the index has little impact on performance.
Using a unique constraint is as adding an index but without having the improved searches? Thank you for your answer!
1

you can make a conditional unique index :

CREATE UNIQUE INDEX names ON (name,lastname) WHERE (_deleted is NOT null);

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.