Binary Lion Studios

I code for fun and for food.

Alter table in SQLite when table contains data

SQLite’s alter table command only supports renaming the table and adding a column. If you need to alter a column (say, to change it’s length), the high-level process looks like this: export the data, drop the table, recreate the table with the updated column, then import the data. You can use SQLite’s dot commands to achieve that with minimal fuss.

1
2
3
4
5
6
7
8
$ sqlite3 dbfile.db
sqlite> .mode insert [tablename]
sqlite> .output [tablename].txt
sqlite> select * from [tablename];
sqlite> drop table [tablename];
sqlite> create table [tablename] ...;
sqlite> .read [tablename].txt
[ctrl+d]

If you’re using Django, it’ll take care of creating the table for you. Just update your models.py to reflect your new changes, then the workflow looks like this:

1
2
3
4
5
6
7
8
9
$ sqlite3 dbfile.db
sqlite> .mode insert [tablename]
sqlite> .output [tablename].txt
sqlite> select * from [tablename];
sqlite> drop table [tablename];
[ctrl+d]
$ python manage.py syncdb
sqlite> .read [tablename].txt
[ctrl+d]

You could also consider looking at the South project which is billed as intelligent schema and data migrations for Django.