23. ALTER TABLE: changing a table that holds data

Add, rename and drop columns, rename tables, and the safe way to make every other change.

Tables change as the shop grows

A table is rarely right forever. The shop starts sending receipts by email and needs an email column; a column name turns out to be unclear; a column is no longer used. ALTER TABLE changes a table without losing the rows in it. In SQLite (and Phai SQL) it can do four things:

StatementWhat it does
ALTER TABLE t ADD COLUMN ...adds a column at the end
ALTER TABLE t RENAME TO new_namerenames the table
ALTER TABLE t RENAME COLUMN a TO brenames a column
ALTER TABLE t DROP COLUMN cremoves a column and its data

Everything else (a column's type, NOT NULL, CHECK, a default) is changed with a recipe at the end of this chapter.

ADD COLUMN

Add a column for the customer's email:

ALTER TABLE customer ADD COLUMN email TEXT;
SELECT id, name, email FROM customer LIMIT 3;
idnameemail
1Somchai JaideeNULL
2Malee SrisukNULL
3Anan WongsaNULL
3 rows

The new column goes at the end of the table, and every row already there gets its default value, here NULL because we gave none. Give a DEFAULT and the old rows get that instead. Mark every product as on sale (1) to begin with:

ALTER TABLE product ADD COLUMN on_sale INTEGER NOT NULL DEFAULT 1;
SELECT id, name, on_sale FROM product LIMIT 3;
idnameon_sale
1Coffee1
2Green Tea1
3Orange Juice1
3 rows

The rules come from that: the old rows need a value, so a few column definitions can't be added this way.

A NOT NULL column needs a default that isn't NULL, or the old rows would break the rule at once:

ALTER TABLE customer ADD COLUMN points INTEGER NOT NULL;
Error: Cannot add a NOT NULL column with default value NULL

A UNIQUE or PRIMARY KEY column can't be added this way at all:

ALTER TABLE customer ADD COLUMN member_no INTEGER UNIQUE;
Error: Cannot add a UNIQUE column

And the default must be a fixed value, not something worked out when the row is written, such as the time now:

ALTER TABLE customer ADD COLUMN created TEXT DEFAULT CURRENT_TIMESTAMP;
Error: Cannot add a column with non-constant default

For a UNIQUE column, add a plain column and then a UNIQUE INDEX on it (chapter 25). For "the time the row was made", add the column with no default, fill the old rows with an UPDATE, and let the program write the time for new rows.

RENAME TO: a new name for a table

ALTER TABLE customer RENAME TO client;
SELECT name, city FROM client LIMIT 3;
namecity
Somchai JaideeBangkok
Malee SrisukChiang Mai
Anan WongsaBangkok
3 rows

The rename is more careful than it looks: every other table, view, index and trigger that names the table is rewritten to the new name. orders pointed at customer; look at how it is defined now (sqlite_schema is the table where the database keeps every definition):

SELECT sql FROM sqlite_schema WHERE name = 'orders';
sql
CREATE TABLE orders ( id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES "client"(id), ordered TEXT NOT NULL, status TEXT NOT NULL )
1 row

Its foreign key now says REFERENCES "client"(id). Let's put the old name back before we go on:

ALTER TABLE client RENAME TO customer;
✓ Done

RENAME COLUMN

Say the shop wants "phone" to mean the shop's landline, and the customers' numbers to be called mobile. To show that views follow too, first make a view that uses the column:

CREATE VIEW contact AS SELECT name, phone FROM customer;
ALTER TABLE customer RENAME COLUMN phone TO mobile;
SELECT name, mobile FROM customer WHERE city = 'Phuket';
namemobile
Pim Chaiya086-555-0101
Siriporn KaewdeeNULL
2 rows

The view was rewritten with the column's new name:

SELECT sql FROM sqlite_schema WHERE name = 'contact';
sql
CREATE VIEW contact AS SELECT name, mobile FROM customer
1 row

The database rewrites only what it keeps itself: tables, views, indexes, triggers. The SQL inside your programs is not changed. A program that still says SELECT phone FROM customer gets "no such column" the day after the rename. Search your code for the old name before you rename.

DROP COLUMN

The email idea was dropped. Remove the column, and the data in it with it:

ALTER TABLE customer DROP COLUMN email;
SELECT * FROM customer LIMIT 3;
idnamecitymobilejoined
1Somchai JaideeBangkok081-234-56782025-01-15
2Malee SrisukChiang Mai089-111-22222025-03-02
3Anan WongsaBangkokNULL2025-04-20
3 rows

A column that something else depends on can't be dropped: the table's PRIMARY KEY, a UNIQUE column, a column with an index, a column in a foreign key, or one that a view, trigger or CHECK uses. Category names are UNIQUE:

ALTER TABLE category DROP COLUMN name;
Error: cannot drop UNIQUE column: "name"

And the view contact still uses mobile:

ALTER TABLE customer DROP COLUMN mobile;
Error: error in view contact after drop column: no such column: mobile

Drop what depends on the column first (the view, the index), and then the column, if that is really what you want.

What ALTER can't do, and the safe recipe

There is no ALTER COLUMN in SQLite. To change a column's type, add or remove NOT NULL, CHECK, UNIQUE or a foreign key, change a default, or change the primary key, you build the table again:

  1. Turn foreign keys off (outside the transaction).
  2. BEGIN a transaction, so that it all happens or none of it does.
  3. Create the new table, as you want it, under a new name.
  4. Copy the rows into it with INSERT INTO ... SELECT.
  5. Drop the old table.
  6. Rename the new table to the old name.
  7. Make again the indexes, triggers and views the old table had.
  8. Check the links with PRAGMA foreign_key_check, then COMMIT, and turn foreign keys back on.

Let's give product two rules it should always have had: a price above 0, and stock never below 0. Why turn foreign keys off? With them on, dropping product deletes its rows, and order_item still points at them:

DROP TABLE product;
Error: FOREIGN KEY constraint failed

So, step 1, then steps 2 to 6 in one transaction:

PRAGMA foreign_keys = OFF;
✓ Done
BEGIN;
CREATE TABLE product_new (
  id          INTEGER PRIMARY KEY,
  name        TEXT NOT NULL,
  category_id INTEGER REFERENCES category(id),
  price       REAL NOT NULL CHECK (price > 0),
  stock       INTEGER NOT NULL DEFAULT 0 CHECK (stock >= 0),
  on_sale     INTEGER NOT NULL DEFAULT 1
);
INSERT INTO product_new (id, name, category_id, price, stock, on_sale)
  SELECT id, name, category_id, price, stock, on_sale FROM product;
DROP TABLE product;
ALTER TABLE product_new RENAME TO product;
✓ Done

product had no indexes, triggers or views of its own, so step 7 has nothing to do. Step 8: no broken links, so commit and turn the check back on:

PRAGMA foreign_key_check;
COMMIT;
PRAGMA foreign_keys = ON;
tablerowidparentfkid
no rows

All 12 products came across, and the new rule holds:

SELECT COUNT(*) FROM product;
COUNT(*)
12
1 row
UPDATE product SET stock = stock - 5 WHERE id = 3;
Error: CHECK constraint failed: stock >= 0

Orange Juice has 0 in stock, so taking 5 more would go below 0: refused.

Keep the order: new table first, rename it last. If you renamed the old table first (product to product_old), the rename would carefully rewrite order_item's foreign key to point at product_old, and when you dropped product_old the order items would point at a table that no longer exists.

Before a rebuild, make a copy of the database file. The transaction protects you from a half-done change, but a copy also protects you from a change you got wrong.

  1. Add a column note TEXT to orders, put "leave at the door" on order 15, and show orders 14 and 15.
  2. Rename that column to remark, then drop it.
  3. Rebuild category so that a name can't be empty text: CHECK (name <> ''). Use the recipe, and count the categories at the end.
Show the answer
ALTER TABLE orders ADD COLUMN note TEXT;
UPDATE orders SET note = 'leave at the door' WHERE id = 15;
SELECT * FROM orders WHERE id IN (14, 15);

ALTER TABLE orders RENAME COLUMN note TO remark;
ALTER TABLE orders DROP COLUMN remark;

PRAGMA foreign_keys = OFF;
BEGIN;
CREATE TABLE category_new (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL UNIQUE CHECK (name <> '')
);
INSERT INTO category_new (id, name) SELECT id, name FROM category;
DROP TABLE category;
ALTER TABLE category_new RENAME TO category;
PRAGMA foreign_key_check;
COMMIT;
PRAGMA foreign_keys = ON;
SELECT COUNT(*) FROM category;
idcustomer_idorderedstatusnote
1432026-11-18cancelledNULL
1572026-11-25paidleave at the door
2 rows
tablerowidparentfkid
no rows
COUNT(*)
4
1 row

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made