Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

PostgreSQL ALTER COLUMN


The ALTER TABLE Statement

To change the data type, or the size of a table column we have to use the ALTER TABLE statement.

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

The ALTER 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 the year column of the cars table from INT to VARCHAR(4).

To modify a column, use the ALTER COLUMN statement and the TYPE keyword followed by the new data type:

Example

Change the year column from INT to VARCHAR(4):

ALTER TABLE cars
ALTER COLUMN year TYPE VARCHAR(4);

Result

ALTER TABLE

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 the color column of the cars table.

Use the same syntax as above, use the ALTER COLUMN statement and the TYPE keyword followed by the new data type:

Example

Change the color column from VARCHAR(255) to VARCHAR(30):

ALTER TABLE cars
ALTER COLUMN color TYPE VARCHAR(30);

Result

ALTER TABLE

PostgreSQL Exercises

Test Yourself With Exercises

Exercise:

Write the correct SQL statement to change the data type of the year field from INT to VARCHAR(4):

 cars
 year  VARCHAR(4);
        

Start the Exercise


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.