这个问题是针对性能问题的, 例如,如果我要添加一个唯一约束,例如:
ALTER TABLE Staffs ADD CONSTRAINT test UNIQUE (Company_Name, Staff_ID);
我应该为性能问题添加唯一索引吗?
CREATE UNIQUE INDEX test2 ON Staffs (Company_Name, Staff_ID);
对于主键,我可以看到dba_indexes
系统表中必须有相应的索引,
但我没有看到案例唯一约束的等价物
答案 0 :(得分:1)
嗯,你确定吗?“我没有看到案例唯一约束的等价物”
SQL> create table t23
2 (id number
3 , col1 date)
4 /
Table created.
SQL> alter table t23
2 add constraint t23_uk unique (id)
3 /
Table altered.
SQL> select index_name, uniqueness
2 from user_indexes
3 where table_name='T23'
4 /
INDEX_NAME UNIQUENES
------------------------------ ---------
T23_UK UNIQUE
SQL>
请注意,我们可以使用现有索引,并且它不必是唯一的。但这意味着索引名称可能与约束名称不匹配(这也适用于主键):
SQL> alter table t23 drop constraint t23_uk;
Table altered.
SQL> select index_name, uniqueness
2 from user_indexes
3 where table_name='T23'
4 /
no rows selected
SQL> create index t23_idx on t23(id)
2 /
Index created.
SQL> select index_name, uniqueness
2 from user_indexes
3 where table_name='T23'
4 /
INDEX_NAME UNIQUENES
------------------------------ ---------
T23_IDX NONUNIQUE
SQL> alter table t23
2 add constraint t23_uk unique (id)
3 /
Table altered.
SQL>
非唯一索引是否强制执行唯一约束?是的确如此:
SQL> insert into t23 values (1, sysdate)
2 /
1 row created.
SQL> r
1* insert into t23 values (1, sysdate)
insert into t23 values (1, sysdate)
*
ERROR at line 1:
ORA-00001: unique constraint (APC.T23_UK) violated
SQL> drop index t23_idx
2 /
drop index t23_idx
*
ERROR at line 1:
ORA-02429: cannot drop index used for enforcement of unique/primary key
SQL>
我们可以检查数据字典以查看哪个索引与约束相关联:
SQL> select constraint_name, constraint_type, index_name
2 from user_constraints
3 where table_name = 'T23'
4 /
CONSTRAINT_NAME C INDEX_NAME
------------------------------ - ------------------------------
T23_UK U T23_IDX
SQL>