Drop Column Is Metadata Only
ALTER TABLE DROP COLUMN finishes instantly regardless of table size because only catalog metadata flips; old bytes stay in the heap until a rewrite.
Code
-- DROP COLUMN 不会重写表:只改目录元数据,存量行的旧字节原样留在堆里
CREATE TABLE devices (
id int PRIMARY KEY,
name text NOT NULL,
legacy_os text
);
INSERT INTO devices (id, name, legacy_os) VALUES (1, 'sensor-1', 'win-xp');
ALTER TABLE devices DROP COLUMN legacy_os; -- 瞬时完成,与表大小无关
-- 目录视角:列还在,只是被标记为已删除(attisdropped = t)
SELECT attname, attisdropped
FROM pg_attribute
WHERE attrelid = 'devices'::regclass AND attnum > 0
ORDER BY attnum;
-- 旧列名立即失效:SELECT legacy_os 会报 column does not exist
-- 同名列可以马上重建,与旧数据互不干扰
ALTER TABLE devices ADD COLUMN legacy_os text;
INSERT INTO devices (id, name, legacy_os) VALUES (2, 'sensor-2', 'linux');
SELECT * FROM devices ORDER BY id;Inside the snippet
Several statements share this file — SELECT / INSERT / CREATE / ALTER, with devices 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.
Using it
Run the statement against the devices table.
Key statements
ALTER TABLE devices DROP COLUMN legacy_os; -- 瞬时完成,与表大小无关
SELECT attname, attisdropped
FROM pg_attribute
WHERE attrelid = 'devices'::regclass AND attnum > 0
ORDER BY attnum;
CREATE TABLE devices (
id int PRIMARY KEY,
name text NOT NULL,
legacy_os text
);
INSERT INTO devices (id, name, legacy_os) VALUES (1, 'sensor-1', 'win-xp');
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.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.
FAQ
- Which relations are involved here?
- `devices`, `pg_attribute`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.