How to make a column non-nullable with a default value in Liquibase for a non-empty table?

36 Views Asked by At

I am working with Liquibase to modify an existing table by adding a new column and making it non-nullable with a default value. The challenge I'm facing is that the table already contains data.

Here is what I have attempted in my changelog XML:

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
        xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
        http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.0.xsd">

    <changeSet id="ajouter_colonne_non_null" author="me">
        <addColumn tableName="my_table">
            <column name="list_index" type="int4">
               <constraints nullable="false" />
            </column>
        </addColumn>

    </changeSet>

</databaseChangeLog>

The error message I receive is:

ERROR: column "list_index" of relation "my_table" contains null values [Failed SQL: (0) ALTER TABLE

How can I correctly add a column to an existing table in Liquibase, make it non-nullable, and set a default value for existing rows with NULL in that column, considering the table is not empty?

0

There are 0 best solutions below