更改列

本文介绍更改列的场景以及用法。

更改列的名称

create  table  sss( id  int primary key ,name string ,card int);
alter table sss rename column name to names;

更改列的长度

create  table cust (
  cardno varchar(10),
  name  string,
  email string,
  age int,
  sal decimal(10,2)
);

更改字段长度

alter table cust alter cardno type varchar(20);

更改列的类型

情景一:更改字段类型(主键)

主键的字段的数据类型(如int改成string或varchar)不能被执行,只能通过重建表,然后导入数据。

情景二:更改字段类型(非索引字段)

string改成varchar(n),必须保证n大于现有数据的最大长度,否则会导致数据缺失。

要更改数据的类型,首先要将会话变量设置为true,可以理解为先开会话,后改数据类型。

set enable_experimental_alter_column_type_general = true;

int类型改为string类型

alter table cust alter age type string;

DECIMAL改为string

alter table cust alter sal type string;

情景三:更改字段数据类型(索引字段)

如果所在字段有索引(并且不能是主键),比如修改age的数据类型

create table cust (
  cardno varchar(10),
  name string,
  email string,
  age int,
  sal decimal(10,2)index(age)
);

开启会话变量

set enable_experimental_alter_column_type_general = true;

先删除索引

show index from cust;

drop index cust@cust_age_idx;

修改数据类型

alter table cust alter age type string;
explain select * from cust where age='20';
                                       info
-----------------------------------------------------------------------------------
  distribution: full
  vectorized: true

  • filter
  │ estimated row count: 1
  │ filter: age = '20'
  │
  └── • scan
        estimated row count: 1 (100% of the table; stats collected 2 minutes ago)
        table: cust@primary
        spans: FULL SCAN

添加索引

create index custbak_index on cust(age);
 explain select * from cust where age='20';
│ filter: age = '20'
  │
  └── • scan
        estimated row count: 1 (100% of the table; stats collected 2 minutes ago)
        table: cust@primary
        spans: FULL SCAN
                                        info
------------------------------------------------------------------------------------
  distribution: local
  vectorized: true

  • index join
  │ estimated row count: 1
  │ table: cust@primary
  │
  └── • scan
        estimated row count: 1 (100% of the table; stats collected 14 minutes ago)
        table: cust@custbak_index
        spans: [/'20' - /'20']