Psql Add Column With Default Value

5 min read

Adding a new column to an existing table is a routine database operation, but doing so with a default value in PostgreSQL requires a nuanced understanding of how the engine handles metadata, table locking, and data rewriting. Whether you are a developer iterating on a schema or a DBA managing a high-traffic production system, the syntax you choose—and the version of PostgreSQL you are running—can mean the difference between an instantaneous migration and a prolonged outage.

This guide explores the ALTER TABLE ... ADD COLUMN command with default values, covering syntax variations, performance implications across versions, and best practices for safe schema evolution.

Understanding the Basic Syntax

At its core, the command to add a column with a default value follows the standard SQL ALTER TABLE syntax. The critical clause is DEFAULT, followed by the expression or literal value you want assigned to existing and future rows Worth knowing..

ALTER TABLE table_name
ADD COLUMN column_name data_type DEFAULT default_value;

As an example, to add a boolean is_active column to a users table that defaults to true:

ALTER TABLE users
ADD COLUMN is_active boolean DEFAULT true;

When this command executes, PostgreSQL performs two distinct logical actions:

  1. Catalog Update: It updates the system catalogs (pg_attribute, pg_attrdef) to register the new column and its default expression. That said, 2. Data Population (Version Dependent): It determines how existing rows receive this value.

The Critical Distinction: PostgreSQL 11 and Later vs. Older Versions

The most important factor in planning this operation is your PostgreSQL version. The behavior changed drastically in PostgreSQL 11 Simple, but easy to overlook. Simple as that..

PostgreSQL 11+: The "Fast Default" Optimization

Starting with version 11, PostgreSQL introduced an optimization for adding columns with constant default values (e.g., DEFAULT 'text', DEFAULT 0, DEFAULT true, DEFAULT now()) Practical, not theoretical..

It does not physically rewrite the table.

Instead, it stores the default value in the system catalog (pg_attrdef). When a query reads an existing row that lacks the new column physically (because the row was created before the ALTER TABLE), the executor fetches the default value from the catalog on the fly.

Implications:

  • Speed: The operation completes in milliseconds, regardless of table size (terabytes of data? No problem).
  • Locking: It requires only an ACCESS EXCLUSIVE lock for a very brief moment (catalog update), minimizing disruption.
  • Storage: No immediate disk space spike.

Caveat: This optimization only applies to immutable (constant) defaults. It does not apply to volatile functions like random(), uuid_generate_v4(), or nextval('seq') (though nextval is technically stable, it is often treated carefully). If you use DEFAULT gen_random_uuid(), PostgreSQL must evaluate that function for every existing row, triggering a full table rewrite Not complicated — just consistent..

PostgreSQL 10 and Older: The Full Table Rewrite

On versions 10 and below, any ADD COLUMN ... DEFAULT command triggers a full table rewrite. PostgreSQL physically updates every single row on disk to write the default value into the new column slot Nothing fancy..

Implications:

  • Duration: Proportional to table size. A 100GB table could take hours.
  • Locking: Holds an ACCESS EXCLUSIVE lock for the entire duration. No reads or writes can occur on the table.
  • Bloat: Doubles disk usage temporarily (old version + new version of rows) until VACUUM reclaims space.

If you are on an older version, you must use the "Three-Step Workaround" (detailed below) to avoid downtime Worth knowing..

Handling Volatile Defaults and Expressions

Even on modern PostgreSQL, certain defaults force a rewrite because the value must be calculated per row at the moment of the ALTER TABLE Easy to understand, harder to ignore. Took long enough..

Scenarios forcing a rewrite (All Versions):

  • DEFAULT random()
  • DEFAULT uuid_generate_v4()
  • DEFAULT now() (Note: now() is stable per transaction, but usually treated as requiring evaluation for existing rows in older versions; in PG11+, now() is often optimized if the planner recognizes it, but gen_random_uuid() definitely forces a rewrite).
  • DEFAULT (some_immutable_function()) — Wait, immutable functions ARE optimized in PG11+. Only volatile functions force a rewrite in PG11+.

Correction for PG11+: If the default is an immutable function (e.g., DEFAULT md5(random()::text || clock_timestamp()::text) is volatile, but DEFAULT lower('ABC') is immutable), PG11+ can optimize it. Even so, it is safer to assume volatile functions (random, uuid_generate_v4, nextval) trigger rewrites Simple, but easy to overlook..

The Safe Migration Pattern: Three-Step Workaround

For large tables on older versions, or when using volatile defaults on any version, use this pattern to avoid long locks and rewrites. This is the industry standard for zero-downtime migrations.

Step 1: Add the Column Without a Default

ALTER TABLE users ADD COLUMN last_login timestamp;
  • PG11+: Instant metadata change.
  • PG10-: Instant metadata change (no rewrite because no default).
  • Result: Column exists, all existing rows are NULL. New inserts will be NULL unless the application provides a value.

Step 2: Backfill Data in Batches

Update existing rows in small chunks (e.g., 1,000–10,000 rows per transaction) to avoid long-running transactions and lock contention Not complicated — just consistent..

-- Example using a loop in a DO block or application code
UPDATE users
SET last_login = created_at -- or '1970-01-01'::timestamp
WHERE id BETWEEN 1 AND 10000
  AND last_login IS NULL;
  • Run this repeatedly (updating the WHERE clause window) until row count affected is 0.
  • This allows concurrent traffic to continue reading/writing the table.

Step 3: Add the Default Constraint

Once the backfill is complete (or "caught up" enough), add the default for future inserts.

ALTER TABLE users ALTER COLUMN last_login SET DEFAULT now();
  • This is a fast catalog update on all supported versions.

Step 4 (Optional): Add NOT NULL Constraint

If the column must be mandatory, validate the data first, then add the constraint. In PG12+, use NOT VALID + VALIDATE CONSTRAINT to avoid a full table scan lock.

-- PG12+
ALTER TABLE users ADD CONSTRAINT users_last_login_not_null CHECK (last_login IS NOT NULL) NOT VALID;
ALTER TABLE users VALIDATE CONSTRAINT users_last_login_not_null;

-- Older versions (requires full scan lock)
ALTER TABLE users ALTER COLUMN last_login SET NOT NULL;

Adding Columns with NOT NULL and Default Simultaneously

A common requirement is adding a mandatory column with a default But it adds up..

ALTER TABLE products
ADD COLUMN status varchar(20) DEFAULT 'active' NOT NULL;

Behavior:

  • PG11+: Optimized (Fast Default) if 'active' is a constant. The NOT NULL constraint is satisfied implicitly by the default.
  • PG10-: Full table rewrite. Every row gets 'active' written to disk.

Warning: You cannot add a NOT NULL column without a default to a table that already has rows. The command will fail because existing rows would violate the constraint immediately.

Working with SERIAL / `

Brand New Today

Recently Completed

For You

In the Same Vein

Thank you for reading about Psql Add Column With Default Value. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home