Given the following tables:
CREATE TABLE verified_name (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL,
UNIQUE (name, email)
);
CREATE TABLE address (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL,
verified_name_id INTEGER NULL REFERENCES verified_name(id)
);
How can I add an additional constraint that when address.verified_name_id is not NULL, the name and email fields on the address must match the those on the referenced verified_name?
I've tried adding the following to address:
FOREIGN KEY (name, email) REFERENCES verified_name(name, email)
...but that constraint is being applied even when verified_name_id is NULL.
I'm looking for something similar to the partial index syntax with a clause like WHERE verified_name_id IS NOT NULL, but simply appending a clause like that to the FOREIGN KEY constraint doesn't work.
Current undesirable solution:
I can add the following constraints to verified_name:
UNIQUE (name, email),
UNIQUE (id, name, email)
And the following constraint to address:
FOREIGN KEY (verified_name_id, name, email) REFERENCES verified_name(id, name, email)
...but that creates an extra constraint on verified_name that I'd prefer not to have (it's a valid logical constraint, but it's also superfluous and there are minor performance implications).
MATCH SIMPLE. I hadn't realized that was how it worked. That satisfies my requirement. – Jim Stewart Dec 05 '13 at 17:52SELECT name, email FROM addresssince now it has to look in two tables on disk? i.e. in another similar data model where integrity isn't this important but it does get queried a lot, would the denormalized model be the better choice? – davidtgq Oct 12 '17 at 15:46