Changing table structure

Topic 4 of 4 in Designing databases11 min readBeginnerFree course

Overview

Databases outlive the first version of the application that uses them. Requirements change: a new field is needed, a name was a bad choice, a rule must be tightened. You can’t drop the table and start again — it’s full of real data. ALTER TABLE changes a table’s structure in place, keeping its rows. Doing that safely on a live system is a core professional skill.

Changing a table with ALTER TABLE. ADD COLUMN: ALTER TABLE customers ADD COLUMN loyalty_points integer NOT NULL DEFAULT 0. RENAME: ALTER TABLE customers RENAME COLUMN phone TO phone_number. ALTER TYPE: ALTER TABLE products ALTER COLUMN stock TYPE bigint. ADD CONSTRAINT: ALTER TABLE products ADD CONSTRAINT name_not_blank CHECK (name <> ‘’). DROP COLUMN: ALTER TABLE customers DROP COLUMN loyalty_points. Store each change as a numbered migration file (001_create_tables.sql, 002_add_loyalty.sql …) in version control, so every copy of the database reaches the same shape; tools include Flyway, Liquibase or your framework’s migrations. In PostgreSQL, ALTER TABLE runs inside a transaction: if one step fails, ROLLBACK undoes them all. Careful on big tables: some changes, like changing a column type, rewrite the whole table and lock it meanwhile.

Adding a column

SQL
ALTER TABLE products ADD COLUMN description text;

SELECT id, name, description FROM products WHERE id <= 3 ORDER BY id;
Text
ALTER TABLE
 id |         name          | description 
----+-----------------------+-------------
  1 | Ethiopian Yirgacheffe | 
  2 | Colombian Supremo     | 
  3 | Decaf House Blend     | 
(3 rows)

Existing rows get NULL in the new column. If the column must be required, give it a default at the same time — otherwise every existing row would break the NOT NULL rule:

SQL
ALTER TABLE products ADD COLUMN is_featured boolean NOT NULL;
Text
ERROR:  column "is_featured" of relation "products" contains null values
SQL
ALTER TABLE products ADD COLUMN is_featured boolean NOT NULL DEFAULT false;

SELECT id, name, is_featured FROM products WHERE id <= 3 ORDER BY id;
Text
ALTER TABLE
 id |         name          | is_featured 
----+-----------------------+-------------
  1 | Ethiopian Yirgacheffe | f
  2 | Colombian Supremo     | f
  3 | Decaf House Blend     | f
(3 rows)

In modern PostgreSQL, adding a column with a constant default is instant even on huge tables — the default is stored once, not written into every row.

Renaming

Columns and tables can be renamed; the data, indexes and constraints come along:

SQL
ALTER TABLE products RENAME COLUMN is_featured TO featured;
ALTER TABLE employees RENAME TO staff;

SELECT name, title FROM staff WHERE manager_id IS NULL;
Text
ALTER TABLE
ALTER TABLE
    name    | title 
------------+-------
 Maya Singh | CEO
(1 row)

Renaming is instant, but it breaks every query and application that uses the old name. On a live system, renames are usually done in steps — add the new name, update the code, then remove the old one — or avoided altogether.

Changing a type

ALTER COLUMN … TYPE converts the existing values. When PostgreSQL knows how to convert (integer to bigint, numeric to a wider numeric), it just works:

SQL
ALTER TABLE products ALTER COLUMN stock TYPE bigint;
Text
ALTER TABLE

When it doesn’t — say, text to a number — supply a USING expression that computes the new value from the old:

SQL
CREATE TABLE legacy_prices (sku text, price text);
INSERT INTO legacy_prices VALUES ('A1', '12.50'), ('B2', ' 7.00 ');

ALTER TABLE legacy_prices
    ALTER COLUMN price TYPE numeric(10,2) USING trim(price)::numeric;

SELECT * FROM legacy_prices ORDER BY sku;
Text
CREATE TABLE
INSERT 0 2
ALTER TABLE
 sku | price 
-----+-------
 A1  | 12.50
 B2  |  7.00
(2 rows)

If any value can’t be converted, the whole change fails and the table is untouched. Type changes usually rewrite the entire table, holding a lock that blocks other sessions meanwhile — fine for small tables, something to plan for on big ones.

Defaults and NOT NULL

Defaults and NOT NULL can be added and removed separately:

SQL
ALTER TABLE orders ALTER COLUMN status SET DEFAULT 'pending';
ALTER TABLE customers ALTER COLUMN city DROP NOT NULL;

INSERT INTO orders (customer_id, ordered_at) VALUES (9, '2026-12-04 09:00')
RETURNING id, customer_id, status;
Text
ALTER TABLE
ALTER TABLE
 id | customer_id | status  
----+-------------+---------
 25 |           9 | pending
(1 row)

INSERT 0 1

Isha has her first order, and its status came from the new default. Changing a default only affects future inserts — existing rows keep their values.

SET NOT NULL checks every existing row first and fails if any value is NULL:

SQL
ALTER TABLE products ALTER COLUMN category_id SET NOT NULL;
Text
ERROR:  column "category_id" of relation "products" contains null values

The gift card has no category. Fix the data first, then apply the rule.

Adding constraints to existing data

New constraints are checked against all the rows already in the table:

SQL
ALTER TABLE customers
    ADD CONSTRAINT email_lowercase CHECK (email = lower(email));
Text
ALTER TABLE

Every email is already lower case, so the constraint was accepted and will guard all future writes. If some rows violated it, you’d get an error naming one of them, and you’d clean the data with an UPDATE first.

On very large tables, checking every row while holding a lock can be slow. PostgreSQL lets you split the job: ADD CONSTRAINT … NOT VALID applies the rule to new writes immediately without checking old rows, and a later ALTER TABLE … VALIDATE CONSTRAINT … checks the existing rows without blocking normal traffic.

Dropping columns and constraints

SQL
ALTER TABLE products DROP COLUMN description;
ALTER TABLE customers DROP CONSTRAINT email_lowercase;
Text
ALTER TABLE
ALTER TABLE

Dropping a column deletes its data permanently. If a view or another object depends on the column, PostgreSQL refuses unless you add CASCADE — read what it would drop before you do. DROP COLUMN IF EXISTS avoids errors in scripts that may run twice.

Schema changes are transactional

In PostgreSQL — unlike MySQL or Oracle — CREATE, ALTER and DROP can run inside a transaction and be rolled back. A migration that fails half-way leaves no trace:

SQL
BEGIN;
ALTER TABLE products ADD COLUMN weight_grams integer;
ALTER TABLE products ADD CONSTRAINT weight_positive CHECK (weight_grams > 0);
ALTER TABLE products ALTER COLUMN weight_grams SET NOT NULL;   -- fails: existing rows are NULL
COMMIT;

SELECT count(*) AS weight_columns
FROM information_schema.columns
WHERE table_name = 'products' AND column_name = 'weight_grams';
Text
BEGIN
ALTER TABLE
ALTER TABLE
ERROR:  column "weight_grams" of relation "products" contains null values
ROLLBACK
 weight_columns 
----------------
              0
(1 row)

The third step failed, so the COMMIT became a rollback, and the column added in the first step is gone too. No half-migrated table.

Migrations

On a real project, nobody runs ALTER TABLE by hand on production. Each change is written as a migration — a numbered SQL file checked into version control alongside the code:

Text
migrations/
  001_create_tables.sql
  002_add_loyalty_points.sql
  003_add_reviews.sql

A migration tool (Flyway, Liquibase, Sqitch, or the one built into frameworks such as Django, Rails, Laravel and Prisma) records which migrations each database has already run and applies the missing ones in order. Every developer’s laptop, the test server and production then all have exactly the same structure, and you can see who changed what, and when.

Habits that keep migrations safe:

  • One change per migration, small and reviewable.
  • Run each migration in a transaction, so it applies completely or not at all.
  • Never edit a migration that has already run somewhere — write a new one.
  • Think about big tables: prefer additive changes (new columns, NOT VALID constraints, indexes built CONCURRENTLY) and schedule table rewrites for quiet times.

Tip: before running a migration on real data, run it against a recent copy (a pg_restore of last night’s backup is perfect) and time it. “It took a second on my laptop” says little about a table with 200 million rows.

Exercise

A loyalty scheme

Bean & Leaf is launching a loyalty scheme. Alter the customers table: add a column loyalty_points (integer, required, default 0); rename phone to phone_number; and add a constraint named points_not_negative that checks loyalty_points >= 0. Then give Asha (id 1) 120 points, and select id, first_name, phone_number and loyalty_points for customers 1 to 3, ordered by id.

SQL
ALTER TABLE customers
  ADD COLUMN ___;

-- rename phone, add the constraint, award the points, then check

Summary

  • ALTER TABLE changes a table in place: ADD COLUMN, RENAME COLUMN, ALTER COLUMN … TYPE, SET/DROP DEFAULT, SET/DROP NOT NULL, DROP COLUMN.
  • Adding a NOT NULL column needs a DEFAULT so existing rows get a value.
  • New constraints are checked against existing data and fail if any row breaks them — fix the data first, or add them NOT VALID and VALIDATE later.
  • In PostgreSQL, schema changes are transactional: a failed migration can be rolled back completely.
  • Store every change as a numbered migration file in version control, and be careful with changes that rewrite or lock big tables.