PostgreSQL ALTER COLUMN
The ALTER TABLE Statement
To change the data type, or the size of a table column we have to use theALTER TABLE statement.
TheALTER TABLE statement is used to add, delete,or modify columns in an existing table.
TheALTER TABLE statement is also used to add and drop various constraints on an existing table.
ALTER COLUMN
We want to change the data type of theyear column of thecars table fromINTtoVARCHAR(4).
To modify a column, use theALTER COLUMNstatement and theTYPE keyword followed by the new data type:
Example
Change theyear column fromINT toVARCHAR(4):
ALTER COLUMN year TYPE VARCHAR(4);
Result
Note: Some data types cannot be converted if the column has value.E.g. numbers can always be converted to text, but text cannot always be converted to numbers.
Change Maximum Allowed Characters
We also want to change the maximum number of characters allowed in thecolor column of thecars table.
Use the same syntax as above, use theALTER COLUMNstatement and theTYPE keyword followed by the new data type:
Example
Change thecolor column fromVARCHAR(255) toVARCHAR(30):
ALTER COLUMN color TYPE VARCHAR(30);

