Updating Schema in SQLite3

By R. S. Doiel, 2020-04-16

SQLite3 is a handy little database as single file tool. You can interact with the file through largely standard SQL commands and embed it easily into applications via the C libraries that the project supports. It is also available from various popular scripting languages like Python, PHP, and Lua. One of the things I occasionally need to do and always seems to forget it how to is modify a table schema where I need to remove a column1. So here are some of the basics do I can quickly find them later and avoid reading various articles tutorials because the search engines doesn’t return the page in the SQLite documentation.

In the next sections I’ll be modeling a simple person object with a id, uname, display_name, role and updated fields.

Creating a person table

  1. CREATE TABLE IF NOT EXISTS "person"
  2. ("id" INTEGER NOT NULL PRIMARY KEY,
  3. "uname" VARCHAR(255) NOT NULL,
  4. "role" VARCHAR(255) NOT NULL,
  5. "display_name" VARCHAR(255) NOT NULL,
  6. "updated" INTEGER NOT NULL);

Adding a column

We will create a junk column which we will remove later.

  1. .schema person
  2. ALTER TABLE person ADD COLUMN junk VARCHAR(255) NOT NULL;
  3. .schema person

Dropping a column

To drop a column in SQLite you need to actually create a new table, migrate the data into it then drop the old table and finally rename it. It is best to wrap this in a transaction.

  1. BEGIN TRANSACTION;
  2. CREATE TABLE IF NOT EXISTS "person_new"
  3. ("id" INTEGER NOT NULL PRIMARY KEY,
  4. "uname" VARCHAR(255) NOT NULL,
  5. "role" VARCHAR(255) NOT NULL,
  6. "display_name" VARCHAR(255) NOT NULL,
  7. "updated" INTEGER NOT NULL);
  8. INSERT INTO person_new
  9. SELECT id, uname, role, display_name, updated
  10. FROM person;
  11. DROP TABLE person;
  12. ALTER TABLE person_new RENAME TO person;
  13. COMMIT;

  1. The SQL ALTER TABLE table_name DROP COLUMN column_name does not work in SQLite3↩︎