0

I have a database table in PostgreSQL called "item" that have 3 columns

id: UUID
name: VARCHAR
type: VARCHAR

The "id" column is a primary key and there is no other constraint or index in this table.

My requirements are: if two rows have the same name, they should not have the same type which means the same type can not be attached to the same name more than once.

Here is my question:
How to insert a new row with maintaining my previous condition and taking into consideration the race condition that night happen with concurrent transactions?

I have already read about conditional insert (using WHERE NOT EXIST) but it has a caveat as mentioned here: https://stackoverflow.com/a/13342031/7972923

1 Answer 1

1

put unique index on (name,type)

CREATE UNIQUE INDEX your_idx ON items (name, type);

This will ensure that there are no two duplicates on (name, type) tuple which I believe achieves if two rows have the same name, they should not have the same type

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

2 Comments

thanks for the answer, I can also use a unique constraint on multiple columns, right?
Exactly, postgresqltutorial.com/postgresql-indexes/… see multiple columns example

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.