↑↓ 选择 ↵ 打开 ⌫ 改范围 完整检索页

pgsql.cc 提供对 postgresql.org 官网内容的中文翻译,由 Pigsty 团队维护。

受支持版本: 当前版本 (18) / 17 / 16 / 15 / 14
测试与开发版本: 19 / devel
不受支持的版本: 13 / 12 / 11 / 10 / 9.6 / 9.5 / 9.4 / 9.3 / 9.2 / 9.1 / 9.0 / 8.4 / 8.3 / 8.2 / 8.1 / 8.0 / 7.4 / 7.3
历史版本PostgreSQL 7.3 已于 2007 年 11 月结束社区维护,本页译文保留供仍在使用旧版本的读者参考。新系统请看当前版本。

2.6. 修改表 #

当你创建了一个表后发现犯了错误,或者 应用的需求变了,可以删除 该表再重新创建。但如果 表中已经装满数据,或者表被其他数据库对象 (例如外键 约束)引用,这就不是一个方便的选择。因此 PostgreSQL 提供了一族命令来修改现有的 表。

You can

  • 增加列

  • 移除列

  • 增加约束

  • 移除约束

  • 修改默认值

  • 重命名列

  • 重命名表

All these actions are performed using the ALTER TABLE command.

2.6.1. 增加列

要添加一个列,使用这条命令:

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.

2.6.2. 移除列

要删除一个列,使用这条命令:

ALTER TABLE products DROP COLUMN description;

2.6.3. 增加约束

添加约束时使用表约束语法。例如:

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;

系统会立即检查约束,因此只有表中的数据满足约束,才能将其添加。

2.6.4. 移除约束

要删除一个约束,你需要知道它的名字。如果你给它 起了名字,那很容易。否则系统会指定一个 生成的名字,你需要把它找出来。 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.)

2.6.5. 更改默认值

要为列设置新的默认值,使用像这样的命令:

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.

2.6.6. 重命名列

要重命名一个列:

ALTER TABLE products RENAME COLUMN product_no TO product_number;

2.6.7. 重命名表

要重命名一个表:

ALTER TABLE products RENAME TO items;

提交更正

译文有误、术语不当或页面显示问题,请到译文仓库 pgsty/pgdoc 报告译文问题。 英文原文本身的问题,请在当前版本的对应页面向上游反馈;上游不再修订已结束维护的版本。