I have the following table:
CREATE TABLE claim (
claim_number TEXT NOT NULL,
line_id TEXT,
process TEXT NOT NULL
);
I want to add a constraint to it so that the combination of claim_number and line_id is always unique.
In most cases line_id is null and there will only be a single row for that claim number. In some cases there will be multiple rows for a given claim_number and in those cases line_id will always contain a value. The goal here is to be able to have a constraint that forces a unique combination on the (claim_number, line_id) combo so that I can use it as a conflict target in an INSERT...ON CONFLICT DO UPDATE
statement so that the process column can be updated. A UNIQUE constraint won't work because it doesn't evaluate NULL = NULL, which makes sense, but isn't what I need.
I have tried adding an exclusion constraint such as:
ALTER TABLE claim
ADD EXCLUDE ( claim_number WITH =,
line_id WITH IS NOT DISTINCT FROM);
But that fails with:
ERROR: syntax error at or near "IS"
Is there a way to use IS NOT DISTINCT FROM
in an exclusion constraint?
In MSSQL Server, this is done using a Filtered Unique Index, where the filter predicate is that it only indexes rows with non-
NULL
values.I'm not a PostgreSQL expert, but Googling shows it's possible using a "Partial Index": https://www.postgresql.org/docs/current/static/indexes-partial.html