Skip to content
Advertisement

Check constraint before insert a value into the database

I’m trying to create a table to store order_details. The table has a column status that should only be allowed to contain the value true once per each order_id, but may contain the value false multiple times per order_id.

create table order_details (
    id serial, 
    order_id integer not null, 
    status boolean not null
);

I want to do this within the table structure itself. Any help would be appreciated. Thanks in advance.

Advertisement

Answer

You can create a filtered unique index:

create unique index on order_details(order_id)
where status;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement