OCP考试题解析_007:主键和索引

OCP考题解析_007:主键和索引
       先明白,Oracle为什么会为主键自动创建索引?
       
       道理其实简单,如果没有索引,那每次插入的时候检查数据完整性时都要走全表扫?
       
       ㈠ 主键索引与NULL
       
       提这个问题,就像是说,我想改姓李,但我不想李字头上有木字,怎么办?
       
       ㈡ 主键索引是否非唯一?
       
       主键要求对应的列上存在索引,但不一定是唯一索引
       如果列上已经存在索引,就会使用这个索引,如果索引不存在,回自动创建一个,且缺省是唯一索引
       
       建主键时会自动建索引,这个索引在删除主键时会自动删除
       如果在建主键之前,就建了以主键的列作为引导列的索引,这时再建主键时就不会自动建索引了,补建的索引就不会自动删除
       
       ㈢ 主键索引的表空间
       
       如果只有一块磁盘,那建一个表空间还是两个没有啥差别;分开建的前提是具有多块磁盘时才有用
       表及其索引是否放在同一个表空间里面,基本不会影响性能的,这一点在Oracle 10.2的文档里面已经特意说明了
       为了管理方便,应该放在不同的表空间中,如果管理的细些,应该确认让表和索引能够落在不同的物理盘上
         
       为主键的索引指定表空间:
       创建时:
       create table t (a date, b date,constraint pk_t primary key (a) using index tablespace idx) tablespace users;
       创建后:
       alter table t  add constraint pk_t primary key(a)  using index TABLESPACE idx
       

       ㈣ 主键与本地索引


       全局索引指的是索引的分区结构和表的分区结构不同;全局索引可以分区也可以不分区
       本地索引指的是索引的分区结构和表的分区结构相同;本地索引当然是分区了的
       
       主键可以是分区索引,但如果是本地索引,就必须包含表的分区键
       这和Oracle 如何保证纪录唯一有关
       如果unique index key没有partition_key,那么每插入一行的纪录,需要扫描所有的索引分区才能验证整个表上这个记录是否唯一
       否则只能保证它所进入的分区中,是唯一的
       也就是,主键或唯一键含了分区键后,是可以保证分区中就可以搞清楚是否唯一了
       

       测试:

hr@ORCL> drop table t purge;

Table dropped.

hr@ORCL> create table t (id number not null,p_id number)
  2      partition by range (p_id)
  3      (
  4        partition p1 values less than (2),
  5        partition p2 values less than (3),
  6        partition p3 values less than (4),
  7        partition p4 values less than (5),
  8        partition p5 values less than (maxvalue)
  9      );

Table created.

hr@ORCL> insert into t select rownum,decode(mod(rownum,5),0,5,mod(rownum,5)) from dual connect by level<=100000;

100000 rows created.

hr@ORCL> commit;

Commit complete.

hr@ORCL> alter table t add constraint pk_t primary key (id) using index local;
alter table t add constraint pk_t primary key (id) using index local
*
ERROR at line 1:
ORA-14039: partitioning columns must form a subset of key columns of a UNIQUE index


hr@ORCL> alter table t add constraint pk_t primary key (id,p_id) using index local;

Table altered.

       ㈤ OCP_007考题:

Q: 1 Examine the structure of the EMPLOYEES table:

EMPLOYEE_ID NUMBER Primary Key
FIRST_NAME VARCHAR2(25)
LAST_NAME VARCHAR2(25)

Which three statements insert a row into the table? (Choose three.)

A. INSERT INTO employees 
VALUES ( NULL, 'John', 'Smith'); 

B. INSERT INTO employees( first_name, last_name) 
VALUES( 'John', 'Smith'); 

C. INSERT INTO employees 
VALUES ( '1000', 'John', NULL); 

D. INSERT INTO employees (first_name, last_name, employee_id) 
VALUES ( 1000, 'John', 'Smith'); 

E. INSERT INTO employees (employee_id) 
VALUES (1000); 

F. INSERT INTO employees (employee_id, first_name, last_name) 
VALUES ( 1000, 'John', ' '); 

Answer: C, E, F