184

How do you change the column type and also set that column to not null together?

I am trying:

ALTER TABLE mytable ALTER COLUMN col TYPE character varying(15) SET NOT NULL

This returns an error.

What is the right syntax?

2

3 Answers 3

336

This should be correct:

ALTER TABLE mytable
    ALTER COLUMN col TYPE character varying(15),
    ALTER COLUMN col SET NOT NULL
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to apply default value for cells which have null value at once?
@EugenKonkov Off the top of my head, UPDATE mytable SET col = <default value> WHERE col IS NULL
16

Also, if you want to REMOVE NOT NULL constrain in postgresql:

ALTER TABLE mytable 
    ALTER COLUMN email DROP NOT NULL;

1 Comment

This doesn't answer the question.
1

Assuming you only wanted to change the nullability of the column, which would be a more frequent operation than changing the type, you don't need such a complex syntax. There is an easier way.

alter table my_schema.my_table
    alter column my_column
    set not null;

This is the same as in Oracle DB, and probably others as well.

You don't need to provide the type information for the column, again. The database already has the type information for your column, you can simply change the nullability of it using the above syntax.

If you need to change the type as well, then it is probably best to do both operations separately. It will be easier to fix and diagnose a problem in the event that something goes wrong.

In my own personal experience, changing the type of a column is quite a rare thing to want to do, whereas changing the nullability is more often required, sometimes because nulls do not work in expected ways when included as part of a unique key, for example. But this is really beyond the scope of your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.