ALTER TABLE ADD COLUMN Fast Default

Add a NOT NULL column with a constant default on PostgreSQL 11+ without rewriting the table, verified from pg_attribute atthasmissing metadata.

SqlData Integrity

Code

snippet
-- PostgreSQL 11+ 的 fast default:ADD COLUMN 带常量默认值
-- 只改目录、不重写已有行,大表加列也能瞬间完成
CREATE TABLE users (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text NOT NULL
);
INSERT INTO users (email) VALUES ('[email protected]'), ('[email protected]');

ALTER TABLE users ADD COLUMN status text NOT NULL DEFAULT 'active';

-- 目录证据:atthasmissing = true 表示该列的默认值对旧行“缺失”,
-- 读取时由数据库补上;常量本体存在 attmissingval 里
SELECT attname, atthasmissing, attmissingval
FROM pg_attribute
WHERE attrelid = 'users'::regclass AND attname = 'status';

-- 查询时旧行自动呈现默认值;之后新插入的行物理存储该值
SELECT id, email, status FROM users ORDER BY id;

-- 边界:volatile 默认(如 random())仍会触发整表重写

How it works

Several statements share this file — SELECT / INSERT / CREATE / ALTER, with users and pg_attribute among the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

Run the statement against the users table.

Statements that matter

SELECT attname, atthasmissing, attmissingval
FROM pg_attribute
WHERE attrelid = 'users'::regclass AND attname = 'status';
CREATE TABLE users (
id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL
);
INSERT INTO users (email) VALUES ('[email protected]'), ('[email protected]');

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`users`, `pg_attribute` — referenced directly, no join needed.