sqlite

sqlite3 change column default value


How do I change the default value of an existing column in a table in sqlite3?

I have a table named notes with a boolean column named hidden. The default is set to true, I want to set it to false.


Solution

  • New Versions

    SQLite now supports RENAME COLUMN, ADD COLUMN, and DROP COLUMN so you can change a column default by:

    1. Renaming the column: alter table t rename column c to c_old
    2. Adding the column with the new default value: alter table t add c boolean default false
    3. Copying the data: update t set c = c_old
    4. Removing the old column: alter table t drop column c_old

    Thanks to dr fu manchu for a heads up on SQLite updating their ALTER TABLE support.

    Older Versions

    I don't think you can without replacing the whole table. From the fine manual:

    SQL Features That SQLite Does Not Implement

    Complete ALTER TABLE support
    Only the RENAME TABLE and ADD COLUMN variants of the ALTER TABLE command are supported. Other kinds of ALTER TABLE operations such as DROP COLUMN, ALTER COLUMN, ADD CONSTRAINT, and so forth are omitted.

    So there is no way to modify an existing column in SQLite. I think you'll have to create a new table with the appropriate default for hidden, copy all the data over, drop the original notes table, and then rename the new one.