postgresql数据库primary key约束/not null约束/unique约束及default值的添加与删除、列的新增/删除/重命名/数据类型的更改

时间:2021-11-11 17:30:01

如果在建表时没有加primary key约束、not null约束、unique约束、default值,而是创建完表之后在某个字段添加的话

1.primary key约束的添加与删除

给red_packet_refund表id字段添加primary key约束:

alter table red_packet_refund add constraint pk_rpr_id primary key(id);

删除primary key约束:

alter table red_packet_refund drop constraint pk_rpr_id;

2.not null约束的添加与删除

给red_packet_customerinfo表bank_name字段添加not null约束:

alter table red_packet_customerinfo alter column bank_name set not null;

删除bank_name字段上的not null约束:

alter table red_packet_customerinfo alter column bank_name drop not null;

3.unique约束的添加与删除

给red_packet_pay表payment_acc字段添加unique约束:

create unique index uix_rpp_payment_acc on red_packet_pay(payment_acc);

删除payment_acc字段上的unique约束:

drop index if exists uix_rpp_payment_acc cascade;

4.default值的添加与删除

给red_packet_grab表created_date字段添加default值now():

alter table red_packet_grab alter column created_date set default now();

删除created_date字段的default值:

alter table red_packet_grab alter column created_date drop default;

5.列的新增与删除

给red_packet_pay表新增error_msg字段

alter table red_packet_pay add error_msg varchar(100);

删除red_packet_pay表error_msg字段

alter table red_packet_pay drop error_msg;

6.字段数据类型的更改

把red_packet_pay表的amount字段由numeric类型改为varchar类型

alter table red_packet_pay alter amount type varchar(10);

7.字段名字的更改

把red_packet_pay表的amount字段改为premium

alter table red_packet_pay rename amount to premium;

以上sql仅针对postgresql数据库有效。因为平安用的是postgresql数据库,故整理下备用。