更改表字段名,字段类型的SQL语句

新建一张表:

postgres=# create table t1(id int,name varchar(32));
CREATE TABLE
postgres=# insert into t1 values(1,'zth');
INSERT 0 1

添加字段:

postgres=# alter table t1 add column address varchar(32);
ALTER TABLE

给新添加的字段增加约束:
先要给已有的记录设置默认值

postgres=# update t1 set address ='';      
UPDATE 1
postgres=# alter table t1 alter column address set not null;
ALTER TABLE
postgres=# \d t1;
                       Table "schema01.t1"
 Column  |         Type          | Collation | Nullable | Default 
---------+-----------------------+-----------+----------+---------
 id      | character(4)          |           |          | 
 name    | character varying(32) |           |          | 
 address | character varying(32) |           | not null | 

更改表字段类型:

postgres=# alter table t1 alter column address type varchar(38);
ALTER TABLE
postgres=# \d t1;
                       Table "schema01.t1"
 Column  |         Type          | Collation | Nullable | Default 
---------+-----------------------+-----------+----------+---------
 id      | integer               |           |          | 
 name    | character varying(32) |           |          | 
 address | character varying(38) |           |          | 

postgres=# alter table t1 alter column name type varchar(38);       
ALTER TABLE
postgres=# \d t1;
                       Table "schema01.t1"
 Column  |         Type          | Collation | Nullable | Default 
---------+-----------------------+-----------+----------+---------
 id      | integer               |           |          | 
 name    | character varying(38) |           |          | 
 address | character varying(38) |           |          | 

postgres=# alter table t1 alter column id type char(4);         
ALTER TABLE
postgres=# \d t1;
                       Table "schema01.t1"
 Column  |         Type          | Collation | Nullable | Default 
---------+-----------------------+-----------+----------+---------
 id      | character(4)          |           |          | 
 name    | character varying(38) |           |          | 
 address | character varying(38) |           |          | 

更改表字段名:

  postgres=# alter table t1 rename column id to user_id;
    ALTER TABLE

postgres=# \d t1;
                       Table "schema01.t1"
 Column  |         Type          | Collation | Nullable | Default 
---------+-----------------------+-----------+----------+---------
 user_id  | character(4)         |           |          | 
 name    | character varying(38) |           |          | 
 address | character varying(38) |           | not null | 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值