背景:有些表随着业务发展会涉及字段的约束修改
1、历史数据字段容许为空 ,但现在要求不能为空了;
2、原类型不允许为空,但现在允许可以为空了。
drop table default.tttt
CREATE TABLE default.tttt(
id String,
name String
) ENGINE = MergeTree PARTITION BY id ORDER BY id SETTINGS index_granularity = 8192
尝试插入数据:
insert into `default`.tttt values ('0',null)-- 失败
DB::Exception: Expression returns value NULL, that is out of range of type String, at: null)
insert into `default`.tttt values ('1','name1'),('2','name2') --成功
select * from `default`.tttt
id|name |
--|-----|
2 |name2|
1 |name1|
尝试由Nullable转换成非空类型:
alter table `default`.tttt MODIFY COLUMN name Nullable(String) --成功
插入一个空值,用于后面的测试:
insert into `default`.tttt values ('3',null) --成功
select * from `default`.tttt
id|name |
--|-----|
2 |name2|
1 |name1|
3 | |
再尝试由Nullable转换成非空类型:
alter table `default`.tttt MODIFY COLUMN name String --失败,因为记录中存在null值
DB::Exception: Cannot convert NULL value to non-Nullable type (version 19.9.2.4 (official build))
CREATE TABLE default.tttt2(
id Nullable(String),
name Nullable(String)
) ENGINE = MergeTree PARTITION BY id ORDER BY id SETTINGS index_granularity = 8192
创建失败,允许为空值不能用于排序 DB::Exception: Sorting key cannot contain nullable columns (version 19.9.2.4 (official build))
CREATE TABLE default.tttt2(
id String,
name Nullable(String)
) ENGINE = MergeTree PARTITION BY id ORDER BY id SETTINGS index_granularity = 8192
--成功
--直接用空表转换类型
alter table `default`.tttt2 MODIFY COLUMN name String --成功。
结论:
1、空表,Nullable与非空类型可以互转;
2、Nullable字段,如果记录不带有Null值,可以从Nullable转成非空类型;
3、含有null值的字段不允许转成非空类型;
4、Nullable字段不允许用于order by;
本文探讨了在ClickHouse数据库中,如何安全地修改表字段的约束条件,包括从允许空值到不允许空值,反之亦然的过程。通过实例演示了Nullable类型字段与非空类型之间的转换条件及限制。
662

被折叠的 条评论
为什么被折叠?



