How to Alter Table in Sqlite


Create temp table, then do migration

The old table

CREATE TABLE "users" (
	"id"	INTEGER NOT NULL,
	"created_at"	INTEGER NOT NULL DEFAULT CURRENT_TIMESTAMP,
	"password"	TEXT NOT NULL,
	PRIMARY KEY("id" AUTOINCREMENT)
);

Rename table

ALTER TABLE "users" RENAME TO "users_old";

The new table

CREATE TABLE "users" (
	"id"	INTEGER NOT NULL,
	"created_at"	TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
	"password"	TEXT NOT NULL,
	PRIMARY KEY("id" AUTOINCREMENT)
);

Migrate data from old table

INSERT INTO "users" (id, created_at, password)
SELECT
	id, created_at, password
FROM "users_old";

Delete old table

DROP TABLE "users_old";

Confirm data

Double check if the created_at type is TIMESTAMP

Notes

  1. Backup data
  2. Data check
  3. If created_at is not timestamp style, need transform.