删除主键约束时是否删除索引

删除主键时是否会删除索引? 答案取决于索引是创建主键时自动创建的,还是创建主键前手工创建的。

测试如下:

--建表

create table hqy_test(id integer) ;

 

--建索引

create (unique) index idx_hqy_id on hqy_test(id) ;

 

--加主键

alter table hqy_test add constraint pk_hqy_id primary key (id);

 

select index_name from user_indexes where index_name='IDX_HQY_ID';
IDX_HQY_ID

 

---删除主键

alter table hqy_test drop constraint pk_hqy_id;

或者:

alter table hqy_test drop primary key; 也是行的。

 

select index_name from user_indexes where index_name='IDX_HQY_ID';
IDX_HQY_ID  ==>没有删除索引

 

--删除索引,增加主键并自动创建索引

drop index idx_hqy_id;

 

alter talbe hqy_test add constraint pk_hqy_id primary key(id) using index;

 

select index_name from user_indexes where index_name='PK_HQY_ID';
PK_HQY_ID  ==>自动创建了索引

 

--删除主键约束

alter table hqy_test drop primary key;

 

select index_name from user_indexes where index_name='PK_HQY_ID';

无 ==>索引被删除了

 

如果删除主键时,希望同时删掉索引,则应该增加drop index选项,从而不管索引是否是创建主键时自动创建的,即:alter table hqy_test drop primary key drop index;

 

其他情况的补充:

如果先手工创建了索引,再增加主键时捎带创建索引,一般不会有什么问题,这时不会自动再去创建索引,但是如果手工创建的索引与自动创建的索引所在表空间不同,则会报错:

create index idx_hqy_id on hqy_test(id) tablespace HQY_T;

 

alter table hqy_test add constraint pk_hqy_id primary key(id) using index tablespace HQY_I;

报错:ORA-01408:such column list already indexed

 

另外,对于有主键的列,如果打算先删掉索引,则会报错:ORA-02429:cannot drop index used for enforcement of unique/primary key

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值