PostgreSQL主键的添加与删除

发布于:2023-09-14 ⋅ 阅读:(322) ⋅ 点赞:(0)

一、创建表主键

(1)创建表时指定主键列
htdb=# create table httab(id serial primary key,name text,age int);
CREATE TABLE
(2)手动指定列添加主键
htdb=# ALTER TABLE httab ADD CONSTRAINT httab_pkey PRIMARY KEY (id); 
ALTER TABLE

查看表结构及约束

htdb=# \d httab
                            Table "public.httab"
 Column |  Type   | Collation | Nullable |              Default              
--------+---------+-----------+----------+-----------------------------------
 id     | integer |           | not null | nextval('httab_id_seq'::regclass)
 name   | text    |           |          | 
 age    | integer |           |          | 
Indexes:
    "httab_pkey" PRIMARY KEY, btree (id)

二、删除表中主键

删除表主键

htdb=# alter table httab drop constraint httab_pkey;
ALTER TABLE

再次查询表结构

htdb=# \d httab
                            Table "public.httab"
 Column |  Type   | Collation | Nullable |              Default              
--------+---------+-----------+----------+-----------------------------------
 id     | integer |           | not null | nextval('httab_id_seq'::regclass)
 name   | text    |           |          | 
 age    | integer |           |          | 

htdb=# 

详情请参阅官方文档:点此跳转


网站公告

今日签到

点亮在社区的每一天
去签到