Set Default Affects Future Inserts Only

ALTER COLUMN SET DEFAULT shapes only future inserts: existing rows keep their values, and DROP DEFAULT just removes the expression without rewriting data.

SqlConfig Management

Code

snippet
-- ALTER COLUMN SET DEFAULT 只约束"之后的 INSERT":
-- 存量行保持原值;DROP DEFAULT 也只删表达式,不回填、不重写
CREATE TABLE documents (
  id         int PRIMARY KEY,
  visibility text NOT NULL
);
INSERT INTO documents (id, visibility) VALUES (1, 'public');

ALTER TABLE documents ALTER COLUMN visibility SET DEFAULT 'private';

-- 存量行不变
SELECT id, visibility FROM documents WHERE id = 1;

-- 只有新行吃到默认值;NOT NULL 列显式插 NULL 仍会被拒
INSERT INTO documents (id) VALUES (2) RETURNING id, visibility;

-- 删掉默认表达式:已有数据不动,之后不带该列的 INSERT 会失败
ALTER TABLE documents ALTER COLUMN visibility DROP DEFAULT;
INSERT INTO documents (id) VALUES (3);
-- ERROR: null value in column "visibility" violates not-null constraint

How it works

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

Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.

Putting it to use

The documents table is the working surface here.

Core lines

SELECT id, visibility FROM documents WHERE id = 1;
CREATE TABLE documents (
  id         int PRIMARY KEY,
  visibility text NOT NULL
);
INSERT INTO documents (id) VALUES (2) RETURNING id, visibility;

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`documents`.