Modifying Table Columns in PostgreSQL (ALTER COLUMN)

Suppose we have the table employees initially like this:

ColumnData TypeConstraints
idSERIALPRIMARY KEY
nameVARCHAR(100)NOT NULL
emailVARCHAR(100)
salaryINTEGER

1. Change data type of salary to NUMERIC(10,2)

ALTER TABLE employees
ALTER COLUMN salary SET DATA TYPE NUMERIC(10,2);

Table now looks like:

ColumnData TypeConstraints
idSERIALPRIMARY KEY
nameVARCHAR(100)NOT NULL
emailVARCHAR(100)
salaryNUMERIC(10,2)

Note: This command does not produce output.

2. Set default value for salary

ALTER TABLE employees
ALTER COLUMN salary SET DEFAULT 50000;

Table now looks like:

ColumnData TypeConstraints
idSERIALPRIMARY KEY
nameVARCHAR(100)NOT NULL
emailVARCHAR(100)
salaryNUMERIC(10,2)DEFAULT 50000

Note: This command does not produce output.

3. Remove default value for salary

ALTER TABLE employees
ALTER COLUMN salary DROP DEFAULT;

Table now looks like:

ColumnData TypeConstraints
idSERIALPRIMARY KEY
nameVARCHAR(100)NOT NULL
emailVARCHAR(100)
salaryNUMERIC(10,2)

Note: This command does not produce output.

4. Add NOT NULL constraint to email

ALTER TABLE employees
ALTER COLUMN email SET NOT NULL;

Table now looks like:

ColumnData TypeConstraints
idSERIALPRIMARY KEY
nameVARCHAR(100)NOT NULL
emailVARCHAR(100)NOT NULL
salaryNUMERIC(10,2)

Note: This command does not produce output.

5. Remove NOT NULL constraint from name

ALTER TABLE employees
ALTER COLUMN name DROP NOT NULL;

Table now looks like:

ColumnData TypeConstraints
idSERIALPRIMARY KEY
nameVARCHAR(100)
emailVARCHAR(100)NOT NULL
salaryNUMERIC(10,2)

Note: This command does not produce output.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top