CREATE TABLE account_members ( id UUID DEFAULT gen_random_uuid (), account_id UUID NOT NULL CONSTRAINT fk_account_members_account REFERENCES accounts (id) ON DELETE CASCADE, user_id UUID NOT NULL CONSTRAINT fk_account_members_user REFERENCES users (id), PRIMARY KEY (id, account_id), CONSTRAINT uq_account_members_account_user UNIQUE (account_id, user_id) ); CREATE FUNCTION ensure_account_has_member () RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN -- Serialises concurrent removals for the same account. Without the lock, two transactions -- removing different members of a two-member account would each still see the other's row. -- No row is found when the account itself is being deleted (cascade), which is allowed. PERFORM 1 FROM accounts WHERE id = OLD.account_id FOR NO KEY UPDATE; IF FOUND AND NOT EXISTS ( SELECT 1 FROM account_members WHERE account_id = OLD.account_id ) THEN RAISE EXCEPTION 'account must have at least one member' USING ERRCODE = 'check_violation', CONSTRAINT = 'ck_account_members_last_member'; END IF; RETURN NULL; END $$; CREATE CONSTRAINT TRIGGER ck_account_members_last_member AFTER DELETE OR UPDATE OF account_id ON account_members DEFERRABLE INITIALLY IMMEDIATE FOR EACH ROW EXECUTE FUNCTION ensure_account_has_member ();