I want to ask you it is possible to unique fields when a column is 1 ?
I have a table sales defined like this:
CREATE TABLE sales
(
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
p_id UUID REFERENCES product(id),
percentage SMALLINT,
expires timestamp NOT NULL,
active SMALLINT DEFAULT 1,
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
)
I want to say when p_id
exists and active
is 1, then I want to avoid that anyone can insert again this.
When active
is 0, then it possible to insert product id with active = 1
2
Answers
If you want to create an unique index based on the combination if p_id and active you could do something like:
With that index no two rows with the same p_id and active = 1 can be inserted into your sales table.
Check out the doc here: https://www.postgresql.org/docs/current/indexes-unique.html
Yes, it is possible.
1/ You can create unique indexes. It can also ensure that no two rows in a table can have the same value in the specified column(s)
You can check out the doc here: https://www.postgresql.org/docs/current/indexes-partial.html
2/ You can create unique constraint. It can ensure that no two rows in a table can have the same value in the specified column(s):