删除主键时是否会删除索引? 答案取决于索引是创建主键时自动创建的,还是创建主键前手工创建的。
测试如下:
--建表
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