Search code examples
mysqlliquibase

Liquibase Add Unique Constraint During Table Creation


I want to add a unique constraint to my table during it's creation. I thought something like this would work but it seems to just do nothing.

<createTable tableName="MY_TABLE">
   <column name="MY_TABLE_ID" type="SMALLINT" autoIncrement="true">
      <constraints primaryKey="true" nullable="false"/>
   </column>
   <column name="TABLE_FIELD" type="SMALLINT">
      <constraints nullable="false" uniqueConstraintName="TABLE_FIELD_ix1"/>
   </column>
   <column name="TABLE_FIELD_TWO" type="SMALLINT">
      <constraints nullable="false" uniqueConstraintName="TABLE_FIELD_ix1"/>
   </column>
</createTable>

I know I can use the addUniqueConstraint tag (and have successfully used it) after I create the table but I wanted to know if that was avoidable.

Basically I want to do this but during the create table portion

<addUniqueConstraint tableName="MY_TABLE"
                     columnNames="TABLE_FIELD, TABLE_FIELD_TWO"
                     constraintName="TABLE_FIELD_ix1"/>

Solution

  • Try adding unique="true" to <constraints>.

        <createTable tableName="MY_TABLE">
           <column name="MY_TABLE_ID" type="SMALLINT" autoIncrement="true">
              <constraints primaryKey="true" nullable="false"/>
           </column>
           <column name="TABLE_FIELD" type="SMALLINT">
              <constraints nullable="false" unique="true" uniqueConstraintName="TABLE_FIELD_ix1"/>
           </column>
           <column name="TABLE_FIELD_TWO" type="SMALLINT">
              <constraints nullable="false" unique="true" uniqueConstraintName="TABLE_FIELD_ix2"/>
           </column>
        </createTable>
    

    This creates two separate unique constraints, one on each of the two fields. It does not create a unique constraint for the set of (TABLE_FIELD, TABLE_FIELD_TWO).