学习目标
学习openGuass数据库中如何对表进行修改
课程学习
1.测试准备
--首先创建一张测试表。 drop table if exists test; create table test( id bigint, name varchar(50) not null, age int default 20, primary key(id) );
复制
2.为表添加字段
--查看表test的信息 \d test --为表test新增一列,列名为sex,数据类型为Boolean: alter table test add column sex Boolean; --执行下面gsql命令,查看表test的信息 \d test
复制
3.删除表中的已有字段
--执行下面的SQL语句,删除刚刚添加的列sex: alter table test drop column sex ; --执行下面gsql命令,再次查看表test的信息 \d test
复制
4.删除表的已有约束
--表test上有一个名叫test_pkey的PRIMARY KEY约束。执行下面的SQL语句,删除这个约束: alter table test drop constraint test_pkey; --执行下面的gsql命令,再次查看表test的信息: \d test --或直接查看约束是否被删除 select * from pg_constraint where conname like 'test_pkey';
复制
5.为表添加约束
--执行下面的SQL命令,为表test添加刚刚删除的主键约束: alter table test add constraint test_pkey primary key(id); --再次查看表test的信息: select * from pg_constraint where conname like 'test_pkey'; \d test
复制
6.修改表字段的默认值
--执行下面的SQL语句,将age的默认值变更为25 alter table test alter column age set default 25; \d test
复制
7.修改表字段的数据类型
alter table test ALTER COLUMN age TYPE bigint; \d test
复制
8.修改表字段的名字
ALTER TABLE test RENAME COLUMN age TO stuage; \d test
复制
9.修改表的名字
--修改表的名字。执行下面的SQL语句,将表test的名字变更为mytest: ALTER TABLE test RENAME TO mytest; \d mytest
复制
10.删除表
DROP TABLE mytest;
复制