开发者

With Liquibase, is there a difference between using a unique <createIndex> and using <column> with a unique constraint?

开发者 https://www.devze.com 2023-03-05 13:22 出处:网络
Liquibase has two ways to define a column as unique: When creating the table, using <constraints> on the column:

Liquibase has two ways to define a column as unique:

  1. When creating the table, using <constraints> on the column:

    <createTable tableName="my_table">
        <column name="my_column">
            <constraints unique="true"
                         uniqueConstraintName="my_table_my_column_uk">
        </column>
    </createTable>
    
  2. After creating the table, using <createIndex>:

    <createTable tableName="my_table">
        <column name="my_column"/>
    </createTable>
    <createIndex tableName="my_table" unique="true"
                 indexName="my_table_my_column_uk">
        <column name="my_column"/>
    </createIndex>
    

Is there any difference between these two approaches for single-column unique keys?

In my own observations with MySQL, there seems to be no difference. Both declarations (above) yield the same SHOW CREATE TABLE result:

...
UNIQUE_KEY `my_table_my_column_uk` (`my_column`)
...

However, does this hold true for all database implementations, or does <createIndex unique="true"> generate different schema output from <constraint unique="true"/> for different databases?

Background: I have a script that has built the liquibase changelog directly from my relational model in the code. The generation script created BOTH declarations if the model indicated the column was unique. I'm cleaning up the generated results and would like to remove one of the declarations, and want to know if th开发者_如何学运维at's appropriate.


See PostgreSQL Documentation:

Note: 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.

So a unique constraint is a concept which is implemented (in PostgreSQL) with a unique index.


I guess it depends on the target DBMS.

In PostgreSQL, Oracle and DB2 there is a differences between a unique index and an unique constraint.

The unique constraint can be the target of a foreign key constraint but the unique index cannot. Don't know if that is the same with MySQL.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号