Alembic: IntegrityError: “column contains null values” when adding non-nullable column

It is because your existing data have no value on that new column, i.e. null. Thus causing said error. When adding a non-nullable column, you must decide what value to give to already-existing data


Alright, existing data should just have “lorem ipsum” for this new column then. But how do I do it? I can’t UPDATE because the column is not there yet.

Use the server_default arg:

op.add_column('mytable', sa.Column(
    'mycolumn', 
    sa.String(), 
    nullable=False, 
    server_default="lorem ipsum", #  <---  add this
))

But, but, I don’t want it to have default value

Drop it afterwards using op.alter_column('mytable', 'mycolumn', server_default=None)

E.g. your upgrade() function would be:

def upgrade():
    op.add_column('mytable', sa.Column('mycolumn', sa.String(), nullable=False, server_default="lorem ipsum"))
    op.alter_column('mytable', 'mycolumn', server_default=None)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)