码迷,mamicode.com
首页 > 其他好文 > 详细

Integrity Constraints

时间:2017-11-04 13:13:34      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:modified   ges   including   默认   child   complete   value   https   uniq   

NOT NULL Integrity Constraints

You can only add a column with a NOT NULL constraint if the table does not contain any rows or if you specify a default value.

这里说了两种情况:列不包含任意行或者指定默认值。

实际上如果列中所有行都不包含null值,也是可以添加 not null 完整性约束的。

 

Unique Constraints

 the database enforces a unique constraint by implicitly creating or reusing an index on the key columns.

意思是说:通过创建或者重用KEY列上的索引强制唯一性约束。

测试示例:

如果KEY列上没有索引的情况:

DROP TABLE EMPLOYEES PURGE;
CREATE TABLE EMPLOYEES AS SELECT * FROM HR.EMPLOYEES;
ALTER TABLE EMPLOYEES ADD CONSTRAINTS ID_UK UNIQUE(EMPLOYEE_ID);
SELECT INDEX_NAME, INDEX_TYPE, UNIQUENESS FROM USER_INDEXES WHERE INDEX_NAME = ID_UK;
INDEX_NAME INDEX_TYPE UNIQUENESS
------------------------------ --------------------------- ---------- ID_UK NORMAL UNIQUE

DROP INDEX ID_UK;


DROP INDEX ID_UK
ORA-02429: 无法删除用于强制唯一/主键的索引

 

ALTER TABLE EMPLOYEES DROP CONSTRAINTS ID_UK;

删除唯一性约束,唯一性索引也会被删除。

 

 

如果KEY列上已有索引的情况:

DROP TABLE EMPLOYEES PURGE;

CREATE TABLE EMPLOYEES AS SELECT * FROM HR.EMPLOYEES;

CREATE INDEX ID_INX ON EMPLOYEES(EMPLOYEE_ID);

ALTER TABLE EMPLOYEES ADD CONSTRAINTS ID_UK UNIQUE(EMPLOYEE_ID);

SELECT INDEX_NAME, INDEX_TYPE, UNIQUENESS FROM USER_INDEXES WHERE INDEX_NAME = ID_INX;

INDEX_NAME                     INDEX_TYPE                  UNIQUENESS
------------------------------ --------------------------- ----------
ID_INX                         NORMAL                      NONUNIQUE

此时会重用之前非唯一性索引。

DROP INDEX ID_INX;


DROP INDEX ID_INX
ORA-02429: 无法删除用于强制唯一/主键的索引

 

可以看出,不管索引是否具有唯一性,都是用于强制KEY列唯一性约束,不能被显式删除。

 

Unless a NOT NULL constraint is also defined, a null always satisfies a unique key constraint. Thus, columns with both unique key constraints and NOT NULL constraints are typical. This combination forces the user to enter values in the unique key and eliminates the possibility that new row data conflicts with existing row data.

Note:

Because of the search mechanism for unique key constraints on multiple columns, you cannot have identical values in the non-null columns of a partially null composite unique key constraint.

 

alter table employees add constraints f_l_name_uk unique(first_name, last_name);

insert into employees(first_name, last_name) values(null, emp);

insert into employees(first_name, last_name) values(null, emp);

ORA-00001: 违反唯一约束条件 (TEST.F_L_NAME_UK)

因此,unique和not null 一般会一起使用。

 

Primary Key Constraints

The database enforces primary key constraints with an index. Usually, a primary key constraint created for a column implicitly creates a unique index and a NOT NULL constraint. Note the following exceptions to this rule:

  • In some cases, as when you create a primary key with a deferrable constraint, the generated index is not unique.

  • ALTER TABLE employees ADD CONSTRAINTS ID_PK PRIMARY KEY(employee_id) INITIALLY DEFERRED;
    
    SELECT INDEX_NAME, UNIQUENESS FROM USER_INDEXES WHERE INDEX_NAME = ID_PK;
    
    INDEX_NAME                     UNIQUENESS
    ------------------------------ ----------
    ID_PK                          NONUNIQUE

    注:可以通过ALTER INDEX INDEX_NAME RENAME TO NEW_INDEX_NAME;来重命名索引。

    或者通过ALTER TABLE TABLE_NAME RENAME CONSTRAINTS CONSTRAINT_NAME TO NEW_CONSTRAINT_NAME;

    可以通过将CONSTRAINT 状态改为 DISABLE 来删除 INDEX,当再次将 CONSTRAINT ENABLE 时,会自动创建同名 INDEX。

    可以通过 ALTER INDEX INDEX_NAME REBUILD TABLESPACE TABLESPACE_NAME; 来改变索引存储位置。

    可以通过 ALTER TABLE TABLE_NAME MOVE TABLESPACE TABLESPACE_NAME; 来改变表存储位置。

  • If a usable index exists when a primary key constraint is created, then the constraint reuses this index and does not implicitly create a new one.(这里也unique约束相同)

By default the name of the implicitly created index is the name of the primary key constraint. You can also specify a user-defined name for an index. You can specify storage options for the index by including the ENABLE clause in the CREATE TABLE or ALTER TABLE statement used to create the constraint.

Foreign Key Constraints

Nulls and Foreign Keys

The relational model permits the value of foreign keys to match either the referenced primary or unique key value, or be null. For example, a user could insert a row into hr.employees without specifying a department ID.

If any column of a composite foreign key is null, then the non-null portions of the key do not have to match any corresponding portion of a parent key.

Parent Key Modifications and Foreign Keys

When a parent key is modified, referential integrity constraints can specify the following actions to be performed on dependent rows in a child table:

No action on deletion or update

In the normal case, users cannot modify referenced key values if the results would violate referential integrity. 

这是在定义外键约束时,默认选项:

如:

alter table employees add constraints id_fk foreign key (MANAGER_ID) references employees;

Cascading deletions

A deletion cascades (DELETE CASCADE) when rows containing referenced key values are deleted, causing all rows in child tables with dependent foreign key values to also be deleted. 

如:

alter table employees add constraints id_fk foreign key (MANAGER_ID) references employees on delete cascade ;

Deletions that set null

A deletion sets null (DELETE SET NULL) when rows containing referenced key values are deleted, causing all rows in child tables with dependent foreign key values to set those values to null. 

如:

alter table employees add constraints id_fk foreign key (MANAGER_ID) references employees on delete set null ;

数据库本身并没有主、外键级联更新的选项。

可以通过触发器实现这个需求。

Indexes and Foreign Keys

As a general rule, Oracle recommends indexing foreign keys in heap-organized tables. An exception for nonpartitioned tables is when the matching unique or primary key is never updated or deleted.

Indexing the foreign keys in child tables provides the following benefits:

  • Prevents a full table lock on the child table. Instead, the database acquires a row lock on the index.

  • Removes the need for a full table scan of the child table. 

Check Constraints

If multiple check constraints exist for a column, then you must design them so that their aims do not conflict. No order of evaluation of the conditions can be assumed. The database does not verify that check conditions are not mutually exclusive.

 

States of Integrity Constraints

As part of constraint definition, you can specify how and when Oracle Database should enforce the constraint, thereby determining the constraint state.

Checks for Modified and Existing Data

The database enables you to specify whether a constraint applies to existing data or future data

强制  future data(UPDATE or INSERT) :

ENABLE 或者 DISABLE

验证 existing data:

VALIDATE 或者 NOVALIDATE

The behavior of VALIDATE and NOVALIDATE always depends on whether the constraint is enabled or disabled. 

对于 Modified Data : DISABLE 和 Existing Data :VALIDATE 组合的情况:

The database disables the constraint, drops its index, and prevents modification of the constrained columns.

例如

ALTER TABLE employees ADD CONSTRAINTS id_pk PRIMARY KEY (employee_id);

ALTER TABLE employees DISABLE VALIDATE CONSTRAINTS id_pk ;

SQL> insert into employees(employee_id) values(1980);

insert into employees(employee_id) values(1980)

ORA-25128: 不能对带有禁用和验证约束条件 (TEST.ID_PK) 的表进行插入/更新/删除

 

Deferrable Constraints

Every constraint is either in a not deferrable (default) or deferrable state. This state determines when Oracle Database checks the constraint for validity. The following graphic depicts the options for deferrable constraints.

技术分享

Nondeferrable Constraints

If a constraint is not deferrable, then Oracle Database never defers the validity check of the constraint to the end of the transaction. Instead, the database checks the constraint at the end of each statement. If the constraint is violated, then the statement rolls back.

Deferrable Constraints

deferrable constraint permits a transaction to use the SET CONSTRAINT clause to defer checking of this constraint until a COMMIT statement is issued. If you make changes to the database that might violate the constraint, then this setting effectively lets you disable the constraint until all the changes are complete.

You can set the default behavior for when the database checks the deferrable constraint. You can specify either of the following attributes:

  • INITIALLY IMMEDIATE

    The database checks the constraint immediately after each statement executes. If the constraint is violated, then the database rolls back the statement.

  • INITIALLY DEFERRED

    The database checks the constraint when a COMMIT is issued. If the constraint is violated, then the database rolls back the transaction.

If a constraint causes an action, then the database considers this action as part of the statement that caused it, whether the constraint is deferred or immediate. 

 

Integrity Constraints

标签:modified   ges   including   默认   child   complete   value   https   uniq   

原文地址:http://www.cnblogs.com/shulin-peng/p/7782534.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!