Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite Modify Column

I need to modify a column in a SQLite database but I have to do it programatically due to the database already being in production. From my research I have found that in order to do this I must do the following.

  • Create a new table with new schema
  • Copy data from old table to new table
  • Drop old table
  • Rename new table to old tables name

That seems like a ridiculous amount of work for something that should be relatively easy. Is there not an easier way? All I need to do is change a constraint on a existing column and give it a default value.

like image 241
Nathan Avatar asked Apr 21 '10 19:04

Nathan


People also ask

How do I edit a table in SQLite?

Summary. Use the ALTER TABLE statement to modify the structure of an existing table. Use ALTER TABLE table_name RENAME TO new_name statement to rename a table. Use ALTER TABLE table_name ADD COLUMN column_definition statement to add a column to a table.

Does ALTER TABLE work in SQLite?

Overview. SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows these alterations of an existing table: it can be renamed; a column can be renamed; a column can be added to it; or a column can be dropped from it.


2 Answers

That's one of the better-known drawbacks of SQLite (no MODIFY COLUMN support on ALTER TABLE), but it's on the list of SQL features that SQLite does not implement.

edit: Removed bit that mentioned it may being supported in a future release as the page was updated to indicate that is no longer the case

like image 98
Daniel DiPaolo Avatar answered Sep 29 '22 10:09

Daniel DiPaolo


If the modification is not too big (e.g. change the length of a varchar), you can dump the db, manually edit the database definition and import it back again:

echo '.dump' | sqlite3 test.db > test.dump 

then open the file with a text editor, search for the definition you want to modify and then:

cat test.dump | sqlite3 new-test.db 
like image 37
Davide Vernizzi Avatar answered Sep 29 '22 12:09

Davide Vernizzi