ALTER COLUMN TYPE With USING

Migrate column types with ALTER COLUMN TYPE and a USING expression that converts existing values, so old rows survive the new domain.

SqlData Integrity

Code

snippet
-- 改列类型:USING 表达式负责旧值到新域的换算,存量行安全迁移
CREATE TABLE invoices (
    id          bigserial PRIMARY KEY,
    total_cents integer NOT NULL
);
INSERT INTO invoices (total_cents) VALUES (1250), (99);

-- integer -> numeric(10,2):USING 把分单位的旧值换算成元
ALTER TABLE invoices
    ALTER COLUMN total_cents TYPE numeric(10,2)
    USING (total_cents::numeric / 100);

SELECT id, total_cents FROM invoices ORDER BY id;

-- text -> integer 反向迁移同样需要显式 USING 转换
ALTER TABLE invoices ADD COLUMN quantity text;
UPDATE invoices SET quantity = '2';
ALTER TABLE invoices
    ALTER COLUMN quantity TYPE integer
    USING quantity::integer;

SELECT id, total_cents, quantity FROM invoices ORDER BY id;

What the code does

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

What the statements actually assemble: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

Run it in the invoices database context.

Statements that matter

CREATE TABLE invoices (
id          bigserial PRIMARY KEY,
total_cents integer NOT NULL
);
SELECT id, total_cents, quantity FROM invoices ORDER BY id;
INSERT INTO invoices (total_cents) VALUES (1250), (99);

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`invoices` — referenced directly, no join needed.