Say we have users and each user can have multiple email addresses
CREATE TABLE emails ( user_id integer, email_address text, is_active boolean)
Some sample rows
user_id | email_address | is_active1 | foo@bar.com | t1 | baz@bar.com | f1 | bar@foo.com | f2 | ccc@ddd.com | t
I want to enforce a constraint that every user has exactly one active address. How can I do this in Postgres? I could do this:
CREATE UNIQUE INDEX "user_email" ON emails(user_id) WHERE is_active=true;
Which would protect against a user having more than one active address, but wouldn't, I believe, protect against all of their addresses being set to false.
If possible I'd prefer to avoid a trigger or a pl/pgsql script, as we don't currently have any of those & it would be difficult to set up. But I would appreciate knowing "the only way to do this is with a trigger or pl/pgsql", if that is the case.