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.

SqlData Integrity

Code

snippet
-- 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

FAQ

Which relations are involved here?
`devices`, `pg_attribute`.