TechBuzzPro

SQLite Table Schema Change: Safe Rebuild Guide

· 5 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

When you need to change a SQLite table's schema—adding a column, changing a type, or reordering fields—you can't just ALTER TABLE for everything. SQLite's ALTER TABLE supports only adding columns and renaming tables/columns. For deeper changes, you must rebuild the table. This guide walks you through the safe, standard procedure: create a new table, copy data, drop the old one, and rename. It also covers backups, foreign keys, and how to avoid data loss.

What You'll Need

  • Access to the SQLite database (command-line tool sqlite3 or a GUI like DB Browser for SQLite)
  • A recent backup of the database file (critical)
  • A clear list of the schema changes you want to make
  • Understanding of your table's indexes, triggers, and views

Step-by-Step

  1. Back up your database. Copy the .db file to a safe location. For example: cp mydb.db mydb_backup.db. This is non-negotiable; if anything goes wrong, you can restore.
  2. Check foreign keys. If your table is referenced by other tables (or references others), you must handle this. Run PRAGMA foreign_keys; to see the current setting. If it returns 1, foreign keys are ON. You'll need to disable them during the rebuild (see step 8).
  3. Get the current schema. Run .schema your_table to see the exact CREATE statement, including indexes and triggers. Save this output—you'll need it to recreate them later.
  4. Create the new table. Write a new CREATE TABLE statement with your desired schema. Give it a temporary name, like your_table_new. Include all columns, types, constraints (PRIMARY KEY, NOT NULL, DEFAULT, etc.) exactly as you want them.
  5. Copy the data. Use an INSERT INTO ... SELECT statement to move data from the old table to the new one. Map columns carefully. For example: INSERT INTO your_table_new (col1, col2, col3) SELECT col1, col2, col3 FROM your_table; If you're adding a column with a default, you can omit it in the SELECT, and the default will be applied. If you need to transform data (e.g., split a name), do it in the SELECT with functions.
  6. Verify the copy. Run SELECT COUNT(*) FROM your_table; and SELECT COUNT(*) FROM your_table_new; to confirm the row counts match. Also spot-check a few rows to ensure data integrity.
  7. Recreate indexes and triggers. For each index on the old table, create the same index on the new table. Use the original CREATE INDEX statements, but change the table name to your_table_new. Do the same for triggers.
  8. Disable foreign keys (if needed). If foreign keys are ON, run PRAGMA foreign_keys=OFF; before dropping the old table. This prevents errors when you drop a table that is referenced.
  9. Drop the old table. Run DROP TABLE your_table;. Be absolutely sure you have a backup and that the new table is correct.
  10. Rename the new table. Run ALTER TABLE your_table_new RENAME TO your_table;. This gives the new table the original name.
  11. Re-enable foreign keys. Run PRAGMA foreign_keys=ON; (if you turned them off).
  12. Test thoroughly. Run queries against the new table, test any application code that uses it, and verify that indexes work (e.g., with EXPLAIN QUERY PLAN).

Common Mistakes

  • Not backing up. The most common and costly mistake. Always have a backup.
  • Forgetting foreign keys. If you drop a table that is referenced, you'll get errors, and you might break referential integrity.
  • Losing indexes and triggers. They don't survive a DROP TABLE. You must recreate them manually.
  • Copying data incorrectly. Column order mismatches or missing columns can lead to data corruption or NULLs where you didn't expect them.
  • Not testing after the rebuild. Even if the copy seems fine, subtle issues can surface later.

Tips

  • Use a transaction. Wrap the entire process in a BEGIN TRANSACTION ... COMMIT. If anything fails, you can ROLLBACK to the original state (though the DROP TABLE is still risky).
  • Test on a copy first. Try the whole procedure on a test database before touching the real one.
  • Use PRAGMA integrity_check after the rebuild to verify the database is not corrupted.
  • Consider using a tool. GUI tools like DB Browser for SQLite can automate some of this, but understanding the manual process is still valuable.
  • Document your schema changes. Keep a migration file (a .sql script) with the steps, so you can repeat them on other environments.

Troubleshooting

  • Foreign key constraint failed during DROP TABLE. You likely forgot to disable foreign keys. Run PRAGMA foreign_keys=OFF; before the DROP, then re-enable after.
  • Data doesn't match after copy. Check your INSERT statement: did you list all columns? Did you use the correct order? Did you accidentally use SELECT * when the column order changed? Review the mapping.
  • Indexes missing after rename. You probably didn't recreate them on the new table before renaming. Recreate them now on the renamed table.
  • Database is locked. Another process is using the database. Close all connections (including your own) and try again. You can also use PRAGMA busy_timeout to wait.
  • Triggers fire unexpectedly. If you have triggers on the table, they may fire during the INSERT INTO ... SELECT. Consider disabling them temporarily with DROP TRIGGER and recreating them after, or use PRAGMA recursive_triggers=OFF (but be careful).
  • Disk full or power failure. If the process is interrupted, you may be left with a partial state. Restore from backup and try again, perhaps with a transaction.

Frequently Asked Questions

  1. Can I use ALTER TABLE to change a column's type? No. SQLite's ALTER TABLE only allows renaming a column or adding a new column. Changing a type requires a rebuild.
  2. What happens to foreign keys that reference the old table? If you drop the old table, those references break. You must either disable foreign keys during the process and update the referencing tables, or ensure that the new table has the same name and structure that satisfies the references.
  3. Is it safe to do this on a live database? It's risky. SQLite allows concurrent reads, but writes are serialized. The rebuild will lock the database for writes. Ideally, do it during maintenance or use a backup and swap files.
  4. Do I need to recreate views? Views are stored as SELECT statements and don't depend on the physical table structure, so they usually work as long as the column names remain the same. But if you rename columns, you'll need to update the views.
  5. Can I automate this process? Yes, you can write a SQL script that does all the steps. This is a good practice for migrations, but always test the script on a copy first.
  6. What if I realize the new schema is wrong after renaming? You can repeat the process: create another new table, copy data, drop the wrong one, rename. Or restore from backup if you haven't made further changes.