pgsql.cc 提供对 postgresql.org 官网内容的中文翻译,由 Pigsty 团队维护。
当你创建了一个表后发现犯了错误,或者 应用的需求变了,可以删除 该表再重新创建。但如果 表中已经装满数据,或者表被其他数据库对象 (例如外键 约束)引用,这就不是一个方便的选择。因此 PostgreSQL 提供了一族命令来修改现有的 表。
You can
增加列
移除列
增加约束
移除约束
修改默认值
重命名列
重命名表
All these actions are performed using the ALTER TABLE command.
要添加一个列,使用这条命令:
ALTER TABLE products ADD COLUMN description text;
新列在表的现有行中最初将填充为空值。
你也可以同时在该列上定义约束, 使用通常的语法:
ALTER TABLE products ADD COLUMN description text CHECK (description <> '');
A new column cannot have a not-null constraint since the column initially has to contain null values. But you can add a not-null constraint later. Also, you cannot define a default value on a new column. According to the SQL standard, this would have to fill the new columns in the existing rows with the default value, which is not implemented yet. But you can adjust the column default later on.
要删除一个列,使用这条命令:
ALTER TABLE products DROP COLUMN description;
添加约束时使用表约束语法。例如:
ALTER TABLE products ADD CHECK (name <> ''); ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no); ALTER TABLE products ADD FOREIGN KEY (product_group_id) REFERENCES product_groups;
非空约束不能写成表约束,添加时应使用以下语法:
ALTER TABLE products ALTER COLUMN product_no SET NOT NULL;
系统会立即检查约束,因此只有表中的数据满足约束,才能将其添加。
要删除一个约束,你需要知道它的名字。如果你给它 起了名字,那很容易。否则系统会指定一个 生成的名字,你需要把它找出来。 psql 命令 \d 在这里 很有帮助;其他接口可能也提供查看表 详细信息的方法。然后命令是:tablename
ALTER TABLE products DROP CONSTRAINT some_name;
This works the same for all constraint types except not-null constraints. To drop a not null constraint use
ALTER TABLE products ALTER COLUMN product_no DROP NOT NULL;
(Recall that not-null constraints do not have names.)
要为列设置新的默认值,使用像这样的命令:
ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77;
要删除任何默认值,使用
ALTER TABLE products ALTER COLUMN price DROP DEFAULT;
This is equivalent to setting the default to null, at least in PostgreSQL. As a consequence, it is not an error to drop a default where one hadn't been defined, because the default is implicitly the null value.
要重命名一个列:
ALTER TABLE products RENAME COLUMN product_no TO product_number;
要重命名一个表:
ALTER TABLE products RENAME TO items;
译文有误、术语不当或页面显示问题,请到译文仓库 pgsty/pgdoc 报告译文问题。 英文原文本身的问题,请在当前版本的对应页面向上游反馈;上游不再修订已结束维护的版本。