新建一张表:
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 |