Is it possible to use IS NOT DISTINCT FROM in an exclusion constraint?

时间:2017-08-30 20:58:39

标签: postgresql constraints postgresql-9.5

I have the following table:

import java.util.Arrays;

public final class A {
    private int[] values;

    public int[] getValues() {
        return values;
    }
}

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 import java.util.Arrays; public class A { private final int[] values; public A(int[] values) { this.values = null == values ? null : Arrays.copyOf(values); } public int[] getValues() { return Arrays.copyOf(values); } } 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:

import java.util.Arrays;

public final class A {
    private final int[] values;

    public A(int[] values) {
        this.values = null == values ? null : Arrays.copyOf(values);
    }

    public int[] getValues() {
        return Arrays.copyOf(values);
    }
}

But that fails with:

CREATE TABLE claim (
    claim_number TEXT NOT NULL,
    line_id TEXT,
    process TEXT NOT NULL
);

Is there a way to use INSERT...ON CONFLICT DO UPDATE in an exclusion constraint?

1 个答案:

答案 0 :(得分:0)

在MSSQL Server中,这是使用Filtered Unique Index完成的,其中过滤谓词是仅对具有非NULL值的行进行索引。

我不是PostgreSQL专家,但谷歌搜索显示可以使用“部分索引”:https://www.postgresql.org/docs/current/static/indexes-partial.html

CREATE UNIQUE INDEX ix_claim_lines ON claim ( claim_number, line_id )
    WHERE line_id IS NOT NULL