Add support for NullsDistinct() / NullsNotDistinct() for Postgre uinque indexes
See original GitHub issueWe have a migration for Postgres that creates an index over two columns, one of them is non-nullable. We want to mimic MsSql behavior (nulls are treated as the same value) and to forbid duplicates like this:
Name OwnerId
------- ----------
User1 NULL
User1 NULL
There’re NullsDistinct() / NullsNotDistinct() extension methods for MsSql server (actually, it does in reverse, allowing nulls to be treated as a distinct values), but there are no such helpers for Postgres.
There are two well-known approaches In PgSql
- Create a secondary index with
WHERE OwnerId IS NULL
filter. Generally it is not a good solution as its nontrivial to apply if you have more than one nullable column in unique index. - Wrap column with
Coalesce(OwnerId, '00000000-0000-0000-0000-000000000000')
expression.
I’d prefer to have a helper for the second approach, or, at least, a way to set a custom expression for .OnColumn()
calls.
Is this a feature you’d like to submit a PR for? No 😦
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:7 (2 by maintainers)
Top Results From Across the Web
“UNIQUE NULLS NOT DISTINCT” IN POSTGRESQL 15
In PostgreSQL, null values were always indexed as distinct values. But as per the improvement in PostgreSQL version 15, this can be changed...
Read more >unique nulls not distinct
Specifying NULLS NOT DISTINCT on unique indexes / constraints will cause NULL to be treated as not distinct, or in other words, equivalently....
Read more >Create unique constraint with null columns - sql
Previously NULL values were always indexed as distinct values, but this can now be changed by creating constraints and indexes using UNIQUE ......
Read more >unique nulls not distinct (…)
Unique constrains accept an optional nulls not distinct modifier to specify that one null value rules out other null values in the same...
Read more >Postgres 15 improves UNIQUE and NULL
When an index is declared unique, multiple table rows with equal indexed values are not allowed. Null values are not considered equal. This...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@lillo42 See previous reply. I assigned it to you. Feel free to un-assign yourself if you’re not that interested.
@fairking , the syntax is: