Postgresql: Conditionally unique constraint

前端 未结 2 631
花落未央
花落未央 2020-11-29 19:06

I\'d like to add a constraint which enforces uniqueness on a column only in a portion of a table.

ALTER TABLE stop ADD CONSTRAINT myc UNIQUE (col_a) WHERE (c         


        
相关标签:
2条回答
  • 2020-11-29 19:47

    it has already been said that PG doesn't define a partial (ie conditional) UNIQUE constraint. Also documentation says that the preferred way to add a unique constraint to a table is ADD CONSTRAINT Unique Indexes

    The preferred way to add a unique constraint to a table is ALTER TABLE ... ADD CONSTRAINT. The use of indexes to enforce unique constraints could be considered an implementation detail that should not be accessed directly. One should, however, be aware that there's no need to manually create indexes on unique columns; doing so would just duplicate the automatically-created index.

    There is a way to implement it using Exclusion Constraints, (thank @dukelion for this solution)

    In your case it will look like

    ALTER TABLE stop ADD CONSTRAINT myc EXCLUDE (col_a WITH =) WHERE (col_b IS null);
    
    0 讨论(0)
  • 2020-11-29 19:59

    PostgreSQL doesn't define a partial (i.e. conditional) UNIQUE constraint - however, you can create a partial unique index. PostgreSQL uses unique indexes to implement unique constraints, so the effect is the same, you just won't see the constraint listed in information_schema.

    CREATE UNIQUE INDEX stop_myc ON stop (col_a) WHERE (col_b is NOT null);
    

    See partial indexes.

    0 讨论(0)
提交回复
热议问题