Question

How do I add an additional column to an existing sqlite 2 database table that have data and indexes associated with it.

It seems like the alter table SQL for that is not available in sqlite2?

Was it helpful?

Solution

From the SqLite FAQ:

SQLite has limited ALTER TABLE support that you can use to add a column to the end of a table or to change the name of a table. If you want to make more complex changes in the structure of a table, you will have to recreate the table. You can save existing data to a temporary table, drop the old table, create the new table, then copy the data back in from the temporary table.

For example, suppose you have a table named "t1" with columns names "a", "b", and "c" and that you want to delete column "c" from this table. The following steps illustrate how this could be done:

BEGIN TRANSACTION;
CREATE TEMPORARY TABLE t1_backup(a,b);
INSERT INTO t1_backup SELECT a,b FROM t1;
DROP TABLE t1;
CREATE TABLE t1(a,b);
INSERT INTO t1 SELECT a,b FROM t1_backup;
DROP TABLE t1_backup;
COMMIT;

OTHER TIPS

It might not be -- sqlite3 has been out for a while. You'll have to create another DB with the table the way you want it and copy the data to it. Or, create a new table, copy the data, drop the original and replace with the new one.

Don't forget that DROP TABLE drops also associated TRIGGERs.

Before you are going to modify the table use the command

.scheme TABLE_TO_MODIFY

that will dump all the current statements that will be dropped including the TRIGGERs that you need to re-create.

Cheers,

Elixon

You don't. Non trivial modification of tables is not supported. What you would need to do is:

  1. Copy the data to a temp table drop the old
  2. create the new table
  3. Copy data from your original table to it
  4. Create the new table
  5. Copy the data from temp into the new table
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top