PostgreSQL
PostgreSQL ALTER COLUMN
Change the data type or maximum size of a column in an existing PostgreSQL table.
The ALTER TABLE statement
To change the data type or size of a table column, use the
ALTER TABLE statement. It can also add, delete, or modify columns
and add or drop constraints on an existing table.
ALTER COLUMN
We will change the data type of the year column in the
products table from INT to VARCHAR(4).
Use ALTER COLUMN, followed by the TYPE keyword and the
new data type:
ALTER TABLE products
ALTER COLUMN year TYPE VARCHAR(4);
PostgreSQL reports:
ALTER TABLE
This confirms that the column definition was changed successfully.
Change the maximum allowed characters
You can use the same syntax to change the maximum length of the
color column from VARCHAR(255) to
VARCHAR(30):
ALTER TABLE products
ALTER COLUMN color TYPE VARCHAR(30);
PostgreSQL reports:
ALTER TABLE
The color column now accepts text with up to 30 characters. Existing
values longer than the new limit must be handled before reducing the column size.
Verify the change
SELECT year, color
FROM products;Further Reading
Continue learning with these related tutorials:
- PostgreSQL Introduction
- PostgreSQL pgAdmin 4
- PostgreSQL Create Table
- PostgreSQL Insert Data
- PostgreSQL Select Data
- PostgreSQL ADD COLUMN
- PostgreSQL UPDATE
- PostgreSQL ALTER COLUMN
- PostgreSQL DROP COLUMN
- PostgreSQL DELETE
- PostgreSQL DROP TABLE
- PostgreSQL Operators
- PostgreSQL SELECT
- PostgreSQL SELECT DISTINCT
- PostgreSQL WHERE
- PostgreSQL ORDER BY
- PostgreSQL LIMIT
- PostgreSQL MIN and MAX
- PostgreSQL COUNT
- PostgreSQL SUM
- PostgreSQL AVG
- PostgreSQL LIKE
- PostgreSQL IN
- PostgreSQL BETWEEN
- PostgreSQL AS
- PostgreSQL Joins
- PostgreSQL INNER JOIN
- PostgreSQL LEFT JOIN
- PostgreSQL RIGHT JOIN
- PostgreSQL FULL JOIN
- PostgreSQL CROSS JOIN
- PostgreSQL UNION
- PostgreSQL GROUP BY
- PostgreSQL HAVING
- PostgreSQL EXISTS
- PostgreSQL ANY
- PostgreSQL ALL
- PostgreSQL CASE
Continue learning
