【问题标题】:In Oracle, does the unique constraint include an index implicitly?在 Oracle 中,唯一约束是否隐式包含索引?
【发布时间】:2015-01-25 15:02:00
【问题描述】:

这个问题是针对性能问题的, 例如,如果我要添加一个唯一约束,例如:

ALTER TABLE Staffs ADD CONSTRAINT test UNIQUE (Company_Name, Staff_ID);

我应该为性能问题添加唯一索引吗?

CREATE UNIQUE INDEX test2 ON Staffs (Company_Name, Staff_ID); 

对于主键,我可以看到dba_indexes系统表中一定有对应的索引, 但我还没有看到 case 唯一约束的等价物

【问题讨论】:

    标签: oracle performance indexing constraints unique


    【解决方案1】:

    “我还没有看到 case 唯一约束的等价物”

    嗯嗯,你确定吗?

    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> 
    

    【讨论】:

    • 对此我感到非常抱歉。它有一个由唯一约束创建的索引
    • 感谢您的评论和好例子!!另一方面,我认为创建唯一索引对我来说没有意义,因为唯一约束不仅具有索引而且还使字段成为键
    猜你喜欢
    • 2011-11-23
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    • 2011-03-18
    • 2020-05-10
    • 2021-11-02
    • 1970-01-01
    相关资源
    最近更新 更多