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.
Code
-- 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 constraintHow 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Name the tables involved in this file.
- `documents`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.