如何在Postgresql中更改new not null列?

时间:2017-04-30 09:41:05

标签: sql postgresql sql-null

我有一个表格,我想添加新的not null varchar(255)

我的查询是:

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 

但我有一个错误:

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

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

2 个答案:

答案 0 :(得分:3)

为了避免您的错误,我们会同时出现两个解决方案:

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;

和另一个:

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

答案 1 :(得分:0)

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

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