Postgres: one boolean true all other false check constraint?

Viewed 740

I'm using Postgres and I have a table with a few columns of type boolean. c1,c2,c3,c4 are the columns (BOOLEAN).

In my model I must have one of them and only one set to true. The other three must be false.

I have added analogous checks (against null, not bool) cases on other columns on the table, like this:

ADD CONSTRAINT only_one_name_not_null CHECK (num_nonnulls(n1, n2, n3, n4) = 1)

I haven't found a solution to do the same thing but with boolean types.

Is there a way to enforce one boolean to true and the others false?

1 Answers

You can convert to numbers and count:

check (( n1::int) + (n2::int) + (n3::int) + (n4::int) = 1)

Note: This assumes that the values are not NULL. Similar logic can be used if NULLs are allowed. They would presumably be treated as false.

Related