AI Hints
Home›PostgreSQL Tutorial›Upsert, Generated Columns, ALTER
PostgreSQL · Lesson 24 of 120

ALTER TABLE

Change a live table.

⏱ 2 min read▶ Video at 20:05🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Tables change as your app grows. A new column, a renamed column, a new rule. Alter table changes a table without losing its data.

  • Add a column
  • Rename
  • New rules

Change the books table

Add column adds a format column, with a default value. Rename column changes a name. Add constraint adds a new rule. Run it. Then backslash d shows the new shape.

query.sqlsql
ALTER TABLE books ADD COLUMN format text NOT NULL DEFAULT 'paperback';
ALTER TABLE books RENAME COLUMN published TO year_published;
ALTER TABLE books ADD CONSTRAINT price_limit CHECK (price < 500);
SELECT title, format, year_published FROM books LIMIT 2;
Output
ALTER TABLE
ALTER TABLE
ALTER TABLE
       title        |  format   | year_published
--------------------+-----------+----------------
 The Silent Orchard | paperback |           2016
 Code of the River  | paperback |           2021
(2 rows)

Safe changes

Adding a column with a default is fast in modern Postgres. Dropping a column is fast too. Changing a column's type may rewrite the whole table. On big tables, test changes first, and run them when it's quiet.

keyvalue
ADD COLUMNfast
DROP COLUMNfast
ALTER TYPEmay rewrite
Big tablestest first

Summary

Alter table adds, renames and changes columns and rules, keeping the data. Next, a quick refresher on joins.

Key takeaways
  • ADD COLUMN
  • RENAME
  • ADD CONSTRAINT
Next up: Joins Refresher — combine tables