The addPrimaryKey Change Type adds a primary key out of an existing column or set of columns.


It is a best practice to normalize the data in your relational database by setting a primary key on one or more of the columns of a table. A table can only have one primary key, regardless of whether that key is single or composite. You can use the primary key to uniquely identify each row in the table.

Running the addPrimaryKey Change Type

To add a primary key to your table, follow these steps:

Step 1: Add the addPrimaryKey Change Type to your changeset with the needed attributes, as shown in the examples.

Step 2: Deploy your changeset by running the update command.

liquibase update

Add new column to existing primary key

If you have already set a primary key on a column, but you realize that column by itself does not provide sufficient uniqueness to each row, you can add an additional column to the existing key. Liquibase returns an error if you try to create a new primary key because one already exists. Instead, follow these steps:

  1. Drop the existing primary key with the dropPrimaryKey Change Type:
    <changeSet author="liquibase-docs" id="dropPrimaryKey-example">
        <dropPrimaryKey  tableName= "existing_table" constraintName="primary_key_constraint"/>
  2. Add new column to the existing table with the addColumn Change Type:
    <changeSet author="liquibase-docs" id="addColumn-example"> 
        <addColumn tableName="existing_table">
            <column name="new_column" type="VARCHAR(256)">
                <constraints nullable="false"/>
  3. Add a composite primary key to the table, including both the new and old columns:
    <changeSet author="liquibase-docs" id="addPrimaryKey-example">
        <addPrimaryKey tableName="existing_table" columnNames="existing_column,new_column" constraintName="primary_key_constraint"/>
  4. Deploy your changes:
    liquibase update

Available attributes

Name Description Required for Supports
catalogName Name of the catalog all
clustered Boolean all
columnNames Name of the column(s) to create the primary key on. Comma separated if multiple all all
constraintName Name of primary key constraint all
forIndexCatalogName all
forIndexName db2, db2z, oracle
forIndexSchemaName all
schemaName Name of the schema all
tableName Name of the table to create the primary key on all all
tablespace all
validate This is true if the primary key has 'ENABLE VALIDATE' set, or false if the primary key has 'ENABLE NOVALIDATE' set. all

Database support

Database Notes Auto Rollback
DB2/LUW Supported Yes
DB2/z Supported Yes
Derby Supported Yes
Firebird Supported Yes
H2 Supported Yes
HyperSQL Supported Yes
INGRES Supported Yes
Informix Supported Yes
MariaDB Supported Yes
MySQL Supported Yes
Oracle Supported Yes
PostgreSQL Supported Yes
Snowflake Supported Yes
SQL Server Supported Yes
SQLite Not Supported No
Sybase Supported Yes
Sybase Anywhere Supported Yes