gpt4 book ai didi

postgresql - ALTER COLUMN TYPE varchar(N) 是否重写 Postgres 9.6 中的表?

转载 作者:行者123 更新时间:2023-11-29 11:58:31 24 4
gpt4 key购买 nike

过去

我们在 Postgres 8.4 中处理这个问题的方法是手动更新 pg_attribute 表:

LOCK TABLE pg_attribute IN EXCLUSIVE MODE;
UPDATE pg_attribute SET atttypmod = 104
WHERE attrelid = 'table_name'::regclass AND
attname = 'column_name';

column_name 是一个 varchar(50) 而我们想要一个 varchar(100),但是表太大了(数千万的行数)并且过于频繁地用于重写。

现在

对于这样一个(至少传闻中的)常见问题,围绕该主题的内容和答案很少而且已经过时。

但是,在看到至少 3 次讨论可能是这种情况的提示后,我开始认为使用较新版本的 Postgres(我们使用的是 9.6),您现在可以运行以下命令:

ALTER TABLE 'table_name' ALTER COLUMN 'column_name' TYPE varchar(100);

...无需重写表格。

这是正确的吗?

如果是这样,您知道 Postgres 文档中关于该主题的一些权威信息吗?

最佳答案

ALTER TABLE 不需要重写。

The documentation说:

Adding a column with a DEFAULT clause or changing the type of an existing column will require the entire table and its indexes to be rewritten.

测试起来很简单:
尝试使用一个空表并查看表的 pg_class 行中的 relfilenode 列是否更改:

SELECT relfilenode FROM pg_class
WHERE relname = 'table_name';

继续阅读文档,您会看到:

As an exception, when changing the type of an existing column, if the USING clause does not change the column contents and the old type is either binary coercible to the new type or an unconstrained domain over the new type, a table rewrite is not needed; but any indexes on the affected columns must still be rebuilt.

由于 varchar(50) 显然可以二进制强制转换为 varchar(100),您的案例不需要重写表,正如上面的测试所证实的那样。

关于postgresql - ALTER COLUMN TYPE varchar(N) 是否重写 Postgres 9.6 中的表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48693373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com