为什么当我设置非空约束时不使用默认值?

Why default is not used when I set not null contratint?

我在 postgresql 数据库中有 table。

对于给定的列,我设置了默认值,然后我希望它是 NOT NULL:

ALTER TABLE "order" ALTER COLUMN last_bill_date SET DEFAULT '-Infinity';
ALTER TABLE "order" ALTER COLUMN last_bill_date SET NOT NULL;

但是第二个语句失败了:

ERROR:  column "last_bill_date" contains null values

为什么当NOT NULL应用于此列时没有使用DEFAULT值?

the documentation:

DEFAULT default_expr

(...)

The default expression will be used in any insert operation that does not specify a value for the column. If there is no default for a column, then the default is null.

更改后的默认表达式无法修改 table 中已存在的行,您应该在设置非空约束之前执行此操作:

update "order"
set last_bill_date = '-Infinity'
where last_bill_date is null