I\'m adding a new, \"NOT NULL\" column to my Postgresql database using the following query (sanitized for the Internet):
ALTER TABLE mytable ADD COLUMN mycol
This worked for me: :)
ALTER TABLE your_table_name ADD COLUMN new_column_name int;
Specifying a default value would also work, assuming a default value is appropriate.
this query will auto-update the nulls
ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) DEFAULT 'whatever' NOT NULL;
Since rows already exist in the table, the ALTER
statement is trying to insert NULL
into the newly created column for all of the existing rows. You would have to add the column as allowing NULL
, then fill the column with the values you want, and then set it to NOT NULL
afterwards.
You have to set a default value.
ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) NOT NULL DEFAULT 'foo';
... some work (set real values as you want)...
ALTER TABLE mytable ALTER COLUMN mycolumn DROP DEFAULT;
Or, create a new table as temp with the extra column, copy the data to this new table while manipulating it as necessary to fill the non-nullable new column, and then swap the table via a two-step name change.
Yes, it is more complicated, but you may need to do it this way if you don't want a big UPDATE on a live table.