154

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?

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236

2 Answers2

276

This should be correct:

ALTER TABLE mytable
    ALTER COLUMN col TYPE character varying(15),
    ALTER COLUMN col SET NOT NULL
Federico Razzoli
  • 4,901
  • 1
  • 19
  • 21
10

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

ALTER TABLE mytable 
    ALTER COLUMN email DROP NOT NULL;
Shoniisra
  • 621
  • 7
  • 6