expression
SQLite: add a compatible column while retaining existing rows
An additive migration can preserve existing records by providing a valid default for a newly required column. Check compatibility with old application versions and test migration on representative data. This example migrates one synthetic existing row. Run in the accompanying Cargo project. Expected stdout (not executed): version: 2; qty: 0 Common mistake: Adding a required column without planning values for existing records.
Formal Syntax & Structure
rust syntaxrust
ALTER TABLE item ADD COLUMN qty INTEGER NOT NULL DEFAULT 0;Working Example
Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> { let mut db = rusqlite::Connection::open_in_memory()?; db.execute_batch("CREATE TABLE item (id INTEGER PRIMARY KEY); INSERT INTO item VALUES (1); PRAGMA user_version = 1;")?; let tx = db.transaction()?; tx.execute_batch("ALTER TABLE item ADD COLUMN qty INTEGER NOT NULL DEFAULT 0; PRAGMA user_version = 2;")?; tx.commit()?; let qty: i64 = db.query_row("SELECT qty FROM item WHERE id = 1", [], |r| r.get(0))?; let version: i64 = db.query_row("PRAGMA user_version", [], |r| r.get(0))?; println!("version: {version}; qty: {qty}"); Ok(())}