Junior — Middle
How can data types be converted in PostgreSQL database?.
sobes.tech AI
Answer from AI
In PostgreSQL, data type conversions can be performed in several ways:
- Explicit conversion (CAST) — using the
CASToperator or the::syntax:
SELECT CAST(column_name AS new_data_type) FROM table_name;
-- or
SELECT column_name::new_data_type FROM table_name;
-
Automatic conversion — PostgreSQL attempts to automatically convert types during operations when possible.
-
Changing column type — using the
ALTER TABLEcommand:
ALTER TABLE table_name ALTER COLUMN column_name TYPE new_data_type USING expression;
For example, to convert text to an integer:
ALTER TABLE users ALTER COLUMN age TYPE integer USING age::integer;
It's important to use USING when the conversion is not trivial, to specify how to convert old data.