ALTER TABLE ... ALTER COLUMN ... TYPE lets you convert an existing column to a new data type without dropping or recreating the table.
Adjusting a column’s type fixes earlier design decisions, aligns with new business rules, improves storage efficiency, or unlocks built-in functions unavailable for the old type.
Use ALTER TABLE table_name ALTER COLUMN column_name TYPE new_data_type
. Add USING expression
to control how old values cast to the new type.
ALTER TABLE Orders ALTER COLUMN total_amount TYPE numeric(12,2);
ALTER TABLE Products ALTER COLUMN price TYPE numeric(10,2) USING price::numeric;
casts each price
value explicitly, preventing implicit-cast errors.
ALTER TABLE Orders ALTER COLUMN total_amount TYPE text USING total_amount::text;
converts money figures to string while preserving values.
ALTER TABLE Customers ALTER COLUMN created_at TYPE timestamp USING to_timestamp(created_at,'YYYY-MM-DD');
guarantees proper parsing of the existing date strings.
Yes. Chain commands with commas: ALTER TABLE Orders RENAME COLUMN total TO total_amount, ALTER COLUMN total_amount TYPE numeric(12,2);
1) Always test casting with SELECT column::new_type
first. 2) Wrap change in a transaction. 3) Create backups for production tables. 4) Add indexes only after the type change to avoid double work.
1) Ignoring USING
when implicit casts fail causes errors. 2) Changing a type referenced by foreign-key or index may block for longer; plan maintenance windows.
Yes. PostgreSQL takes an ACCESS EXCLUSIVE lock, blocking concurrent queries. For large tables, schedule off-hours or use logical replication for zero-downtime migrations.
Yes, but you must run another ALTER COLUMN TYPE back to the original type, possibly with a USING clause. Always keep a backup before altering.
Most type changes rewrite the entire table. PostgreSQL 13+ can skip rewriting for some binary-compatible conversions (e.g., varchar length increase).