0

I'm using postgres 14 and I realised that a Unique Constraint size seems to grow even when null values are being inserted.

ALTER TABLE tablename ADD CONSTRAINT constraint_name UNIQUE column;

Given that Unique Constraints generally don't really consider null as unique, this is rather surprising.

We can achieve the same uniqueness constraint using less disk space by using a partial index as such below.

CREATE UNIQUE INDEX index_name ON "table" ("column") WHERE "column" IS NOT NULL;

Unfortunately it's not as simple as changing unique constraints to use partial unique indexes. You lose capabilities such as ON CONFLICT ON CONSTRAINT and deferred checking. As mentioned here

Is there another way to apply the unique constraint whilst not having null values add up to the disk space?

3
  • Hmmm...are you certain that other, non null data, is not also being inserted at the same time? Commented Feb 15, 2024 at 10:22
  • Yes I have a table with multiple unique constraints on multiple columns and each constraint is the same size despite some columns having 99% null data and others having 1% null data. Commented Feb 15, 2024 at 10:30
  • This is interesting. Formally (null=null) is false, respectively, each null value is unique. Commented Feb 15, 2024 at 10:47

1 Answer 1

2

NULL values are indexed just like all other data. The only way to avoid that is a partial unique index.

You are correct that the check from a partial index cannot be deferred, but it can be used with INSERT ... ON CONFLICT. Just add the appropriate WHERE condition to the conflict target.

Sign up to request clarification or add additional context in comments.

1 Comment

oh interesting, i guess the insert on conflict isnt an issue when replacing with a partial unique index exlcuding nulls then? So the only issue is partial index not being deferrable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.