sql - 向 Redshift 表添加 NOT NULL 列

标签 sql amazon-redshift

我想向包含记录、IDENTITY 字段且其他表具有外键的 Redshift 表添加 NOT NULL 列。

在 PostgreSQL 中,您可以将列添加为 NULL,填充它,然后将其更改为 NOT NULL。

在 Redshift 中,迄今为止我发现的最好的是:

ALTER TABLE my_table ADD COLUMN new_column INTEGER;

-- Fill that column

CREATE TABLE my_table2 (
    id INTEGER IDENTITY NOT NULL SORTKEY,
    (... all the fields ... )
    new_column INTEGER NOT NULL,
    PRIMARY KEY(id)
) DISTSTYLE all;

UNLOAD  ('select * from my_table')
to 's3://blah' credentials '<aws-auth-args>' ;

COPY my_table2 
from 's3://blah' credentials '<aws-auth-args>'
EXPLICIT_IDS;

DROP table my_table;

ALTER TABLE my_table2 RENAME TO my_table;

-- For each table that had a foreign key to my_table:
ALTER TABLE another_table ADD FOREIGN KEY(my_table_id) REFERENCES my_table(id)

这是实现这一目标的最佳方法吗?

最佳答案

您无需加载到 S3 即可实现此目的。

  1. 修改现有表以创建具有默认值的所需列
  2. 以某种方式更新该列(在我的例子中,它是从另一列复制的)
  3. 创建一个新表,其中的列不带默认值
  4. 插入新表(您必须列出列而不是使用 (*),因为顺序可能相同(假设您希望新列位于位置 2)
  5. 删除旧表
  6. 重命名表格
  7. 更改表以提供正确的所有者(如果适用)

例如:

-- first add the column w/ a default value
alter table my_table_xyz
    add visit_id bigint NOT NULL default 0; -- not null but default value

-- now populate the new column with whatever is appropriate (the key in my case)
update my_table_xyz
set visit_id = key;

-- now create the new table with the proper constraints
create table my_table_xzy_new
(
    key bigint not null,
    visit_id bigint NOT NULL, -- here it is not null and no default value
    adt_id bigint not null
);

-- select all from old into new
insert into my_table_xyz_new
select key, visit_id, adt_id
from my_table_xyz;

-- remove the orig table
DROP table my_table_xzy_events;

-- rename the newly created table to the desired table
alter table my_table_xyz_new rename to my_table_xyz;

-- adjust any views, foreign keys or permissions as required

关于sql - 向 Redshift 表添加 NOT NULL 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39914762/

相关文章:

mysql - 使用SQL计算时间

Python 挑战字符串编码

amazon-redshift - 由于内部错误,不支持 Redshift 这种类型的相关子查询模式

ruby-on-rails - 如何使用 PG gem 捕获 PSQL 命令的输出?

date - 从日期列中减去月份

sql - 数据值 "0"在 redshift 中有无效格式错误

php - Doctrine 2 : Update query with query builder

sql - 左连接最大/顶部

mysql - 对用户重新排序 按积分排序的排名

amazon-web-services - 首次运行的查询非常慢