简单的创建一个表:
create table public.food (
id numeric(7) ,
name varchar(10) ,
class varchar(10) ,
count numeric(7) ,
date timestamp
)
修改表名:
alter table public.food rename to food_demo
修改字段名:
alter table public.food_demo rename column id to unique_id
添加一条记录:
insert into public.food_demo(unique_id,name,count,date) values(1,'机器人',7,now())
修改字段类型:
alter table public.food_demo alter column count type numeric(10, 2)
alter table public.food_demo alter column count type varchar(10)
- 当字段里现有的每个项都能用一个隐含的类型转换成新的类型时才可能成功
- 当需要自定义的转换时,使用USING子句
insert into public.food_demo(unique_id,name,count,date) values(7,'机器人7',87654321.12,now())
alter table public.food_demo alter column count type numeric(10,2) using count::numeric(10,2)
- 当字段存在任何约束时,可能转换失败,或者生成奇怪的结果(修改字段类型,先删除约束,最后在建约束)
添加删除省缺值:
alter table public.food_demo alter column count set default '0'
- 不对当前数据生效,在将来insert时生效
- 不设置省缺值,默认为null
alter table public.food_demo alter column count drop default
- 即使删除没有人为设置省缺值的字段,也不会报错,由于默认为null
添加字段:
alter table public.food_demo add column description text
alter table public.food_demo add column description1 text default '无'
- 执行后字段值默认为null,可以设置默认值
删除字段:
alter table public.food_demo drop column description1
- 和这个字段相关的约束也会被删除
alter table public.food_demo drop column description1 cascade
- 授权删除任何依赖该字段的东西
增加字段约束:
alter table public.food_demo add check (name <> '机器人5')
alter table public.food_demo add constraint hzj_definition_constraint unique(unique_id)
alter table public.food_demo add foreign key (name) references robot(name)
alter table public.food_demo add primary key (unique_id)
- 从表name为主键,且主表外键字段值在从表中有
alter table public.food_demo alter column date set not null
- 这个约束会立即检查已有字段,有为null的不通过
删除字段约束:
alter table public.food_demo drop constraint food_demo_name_check
alter table public.robot drop constraint robot_pkey cascade
- 别其他表的字段所约束的字段约束
alter table public.food_demo alter column date drop not null
补充:
创建自增主键:
- 创建表时自动创建自增序列
create table test(
id serial primary key,
age int
)
会自动创建名为表名_字段名_seq的序列,且MAXVALUE=9223372036854775807,其余值为1
- 手动创建一个序列
create sequence
hzj_id_seq
increment 1
minvalue 1
maxvalue 9223372036854775807
start with 1
cache 100
#CYCLE : 序列是否循环使用
#OWNED BY : 指定一个表的字段,可以不指定
select nextval('public.hzj_id_seq') --递增序列并返回新值
select setval('public.hzj_id_seq', 100) --设置序列的当前数值
select setval('public.hzj_id_seq', 200, false) --设置序列的当前数值,是否立即生效
select lastval() --返回最近一次用 nextval 获取的任意序列的数值
select currval('public.hzj_id_seq') --获取指定序列最近一次使用netxval后的数值,没有会报错
alter table public.test drop constraint test_pkey
创建主键
alter table public.test add primary key (id)
设置主键字段默认值
alter table public.test alter column id set default nextval('hzj_id_seq')