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.
Code
-- 改列类型: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
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.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.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.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
- Which tables does this file reference?
- `invoices` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.