liquibase update data based on existing column

Viewed 526

Here, I am new to liquibase and I have a scenario where I need to add a new column to the existing table and have the value of this column based on existing column. However I was able to add column but I couldn't find a way to set default value for this column.

consider I have a table called table_1

id col1 col2
1 11 22
2 12 33
3 13 44

Now I want to add column col3 in the above table and have value of this column same as col2. I am expecting output something like

id col1 col2 col3
1 11 22 22
2 12 33 33
3 13 44 44
2 Answers

Add nullable column with one changeset, then update the values with the second changeset.

    <changeSet id="Add col3" author="me">
        <addColumn tableName="table_1">
            <column name="col3" type="int" />
        </addColumn>
    </changeSet>

    <changeSet id="Update column using another column" author="me">
        <update tableName="table_1">
            <column name="col3" valueComputed="col2" />
        </update>
    </changeSet>

Update column data based on another column

You've marked liquibase SQL, are you using SQL as the preferred language in your changelog?

I think if you are, a SQL statement might work:

-- liquibase formatted sql

-- changeset user1:1651490946175-1
UPDATE TABLENAME SET col3 = col2;

Otherwise, you could use similar syntax in json, yaml.

Related