如何在不允许null的Postgresql数据库中添加列? [英] How can I add a column to a Postgresql database that doesn't allow nulls?

查看:407
本文介绍了如何在不允许null的Postgresql数据库中添加列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下查询(已针对Internet进行了消毒)向我的Postgresql数据库添加新的 NOT NULL列:

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 mycolumn character varying(50) NOT NULL;

每次运行此查询时,都会收到以下错误消息:

Each time I run this query, I receive the following error message:


ERROR:  column "mycolumn" contains null values


我很困惑。我要去哪里错了?

I'm stumped. Where am I going wrong?

注意:我主要使用的是pgAdmin III(1.8.4),但是当我在Terminal中运行SQL时遇到了相同的错误。

NOTE: I'm using pgAdmin III (1.8.4) primarily, but I received the same error when I ran the SQL from within Terminal.

推荐答案

您必须设置默认值。

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;

这篇关于如何在不允许null的Postgresql数据库中添加列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆