简体   繁体   中英

How to alter new not null column in Postgresql?

I have a table that I want to add new not null varchar(255) column

My query is:

alter table poll_management.DASHLETS add column name varchar(255) not null;
update poll_management.DASHLETS as dashlet set name = report.name 
from poll_management.REPORTS as report
WHERE dashlet.id = report.reportdashletid 

But I have an error:

ERROR:  column "name" contains null values
********** Error **********

ERROR: column "name" contains null values
SQL state: 23502

To avoid your error, two solutions come at once:

BEGIN;
  alter table poll_management.DASHLETS add column name varchar(255);
  update poll_management.DASHLETS as dashlet set name = report.name 
from poll_management.REPORTS as report;
  --mind I removed where, cos you need to update ALL rows to have some avlue
  alter table poll_management.DASHLETS alter column "name" set not null;
END;

and the other:

  alter table poll_management.DASHLETS add column name varchar(255) NOT NULL default 'not set';

我发现我的查询必须更改为:

alter table poll_management.DASHLETS add column name varchar(255) not null DEFAULT 'value';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM