Sie sind auf Seite 1von 10

SkillSoft Learning Object

Page 1 of 10

| Print | Contents | Close |

Including constraints in an Oracle9i database


Learning objective

After completing this topic, you should be able to describe, create, and maintain constraints in an Oracle9i database.

1. Defining constraints
A constraint is a rule that you define on a column or a group of columns to prevent invalid data from entering a table. In Oracle, you use constraints to maintain data integrity. For example, if you create an employee table that lists employee names and identification numbers, you may define a constraint to ensure that every identification number is unique. You use constraints to
l l

enforce rules on data when users insert, update, or delete rows in tables prevent the deletion of tables that contain values on which other tables depend provide rules for Oracle tools Oracle Developer, for example

Oracle stores all constraints in the data dictionary. You should give a constraint you define a meaningful name so that you and other developers can identify its function easily. By convention, a full constraint name consists of a short meaningful name for the constraint, the name of the column on which the constraint is defined, and a constraint type abbreviation, separated by underscores. For example, if you define a NOT NULL constraint on the last_name column of the employees table, you should name the constraint name_last_name_nn. If you don't name a constraint, Oracle generates a name using the format SYS_Cn, where n is a unique integer. You create constraints when you create a table, using the following syntax.

CREATE TABLE [schema.]table (column datatype [DEFAULT expr] [column_constraint], ... [table_constraint] [, ...] );

You can define constraints at


l l

table level column level

http://xlibrary.skillport.com/courseware/cbtlib/67002/68153/eng/thin/transcript.html

5/11/2007

SkillSoft Learning Object

Page 2 of 10

table level To define a constraint at table level, you use the following syntax in a CREATE TABLE statement. column, ... [CONSTRAINT constraint_name] constraint_type (column, ...), You define a table-level constraint separately from the column definitions in a CREATE TABLE statement. You can reference one or more columns in the constraint definition. You can define any type of constraint at table level except NOT NULL. This code creates a table named security and defines a table-level PRIMARY KEY constraint named sec_password_pk on the password column. CREATE TABLE security( password VARCHAR2(10), emp_id NUMBER NOT NULL, CONSTRAINT sec_password_pk PRIMARY KEY (password)); column level To define a constraint at column level in a CREATE TABLE statement, you use the following syntax. A constraint at column level references a single column and is included in the column specification. You can define any type of constraint at column level. column [CONSTRAINT constraint_name] constraint_type, This code creates a table named security. The column specification for the emp_id column includes a definition for a column-level NOT NULL constraint named sec_emp_id_nn. CREATE TABLE security( password VARCHAR2(10), emp_id NUMBER (6), CONSTRAINT sec_emp_id_nn NOT NULL, CONSTRAINT sec_password_pk PRIMARY KEY (password));

2. Constraint types
You now need to complete the following matching question.

Question

Oracle provides several data integrity constraints. Match the constraints to their descriptions. Options: 1. UNIQUE

http://xlibrary.skillport.com/courseware/cbtlib/67002/68153/eng/thin/transcript.html

5/11/2007

SkillSoft Learning Object

Page 3 of 10

2. 3. 4. 5.

FOREIGN KEY CHECK NOT NULL PRIMARY KEY

Targets: A. B. C. D. E. Specifies that a column cannot contain null values Specifies that each value in a column must be unique Uniquely identifies each row in a table Enforces a relationship between two tables Specifies a condition that must be true for all values in a column

Answer

The NOT NULL constraint forbids null values in a column and the UNIQUE constraint specifies that all values in a column must be unique. The PRIMARY KEY constraint specifies a column in which unique values identify each row in a table, the FOREIGN KEY constraint establishes a relationship between two tables, and the CHECK constraint specifies a condition that each value in a column must meet.

Oracle integrity constraints include:


l l l l l

NOT NULL UNIQUE PRIMARY KEY CHECK FOREIGN KEY

NOT NULL You can define a NOT NULL constraint at column level only. This code here creates two NOT NULL constraints at column level for the columns emp_id and sales_code. CREATE TABLE commission( emp_id NUMBER(6)NOT NULL comm_pct NUMBER(8,2), sales_code VARCHAR2(8) CONSTRAINT comm_sales_code_nn NOT NULL); Because the code provides no name for the constraint on the emp_id column, Oracle generates a system name for the constraint by default. UNIQUE The column that a UNIQUE constraint references is known as the unique key. If you define a UNIQUE constraint on a group of columns, the columns are known as a composite unique key. A column with a UNIQUE constraint can contain null values.

http://xlibrary.skillport.com/courseware/cbtlib/67002/68153/eng/thin/transcript.html

5/11/2007

SkillSoft Learning Object

Page 4 of 10

CREATE TABLE commission( emp_id NUMBER(6)NOT NULL comm_pct NUMBER(8,2), sales_code VARCHAR2(8) CONSTRAINT comm_sales_code_uk UNIQUE); You can define a single unique key at table level or at column level. You define composite unique keys at table level only. This code defines the UNIQUE constraint comm_sales_code_uk on the sales_code column in the commission table. PRIMARY KEY A primary key is a column or a set of columns in which the values uniquely identify each row in a table. As a result, a PRIMARY KEY constraint enforces both a UNIQUE and a NOT NULL constraint on a column or group of columns. CREATE TABLE security( password VARCHAR2 (10), emp_id NUMBER (6), CONSTRAINT sec_password_pk PRIMARY KEY (password)); A table can have only one PRIMARY KEY constraint. However, the same table can have several UNIQUE constraints. You can define a PRIMARY KEY constraint on a single column at column level or at table level. You can define a composite primary key at table level only. The code shown here defines a table-level PRIMARY KEY constraint named sec_password_pk on the password column. CHECK You can use query constructs in the condition for a CHECK constraint, except for
queries that refer to values in other rows in a table references to the pseudocolumns CURRVAL, NEXTVAL, LEVEL , and ROWNUM l calls to the USER, USERENV, UID, and SYSDATE functions
l l

You can define a CHECK constraint at table level or at column level. The following code here defines a CHECK constraint at column level on the column password. The constraint uses the LENGTH function in the check condition to ensure that the password for each employee is longer than six characters. CREATE TABLE security( password VARCHAR2 (10), CONSTRAINT sec_password_ck CHECK(LENGTH(password)> 6), emp_id NUMBER(6)); FOREIGN KEY

http://xlibrary.skillport.com/courseware/cbtlib/67002/68153/eng/thin/transcript.html

5/11/2007

SkillSoft Learning Object

Page 5 of 10

A foreign key is a column or set of columns in one table the child table that references a primary or unique key in a second or parent table. The values in the foreign key must match the values in the referenced column in the parent table. You use the keyword REFERENCES to identify the parent table and the column or set of columns to which a foreign key refers. CREATE TABLE security( password VARCHAR2 (10) PRIMARY KEY, emp_id NUMBER(6), CONSTRAINT sec_emp_id_fk FOREIGN KEY(emp_id) REFERENCES employees(employee_id));

This code defines the FOREIGN KEY constraint sec_emp_id_fk . It defines the emp_id column as a foreign key that references the employee_id column in the employees table.

You can define a FOREIGN KEY constraint at table level or at column level. When you define a FOREIGN KEY constraint at column level, you omit the FOREIGN KEY keywords.

CREATE TABLE security( password VARCHAR2 (10) PRIMARY KEY, emp_id NUMBER(6)CONSTRAINT sec_emp_id_fk FOREIGN KEY REFERENCES employees(employee_id));

By default, Oracle disallows the updating or deletion of referenced data. To allow users to modify referenced data, you use the keywords
l

ON DELETE CASCADE to specify that Oracle deletes dependent rows in a child table if a user drops the parent table ON DELETE SET NULL to convert dependent foreign key values to null if a user removes a parent value

CREATE TABLE security( password VARCHAR2 (10) PRIMARY KEY, emp_id NUMBER(6) CONSTRAINT sec_emp_id_fk FOREIGN KEY REFERENCES employees(employee_id)) ON DELETE CASCADE); CREATE TABLE security( password VARCHAR2 (10) PRIMARY KEY, emp_id NUMBER(6) CONSTRAINT sec_emp_id_fk FOREIGN KEY REFERENCES employees(employee_id)) ON DELETE SET NULL);

3. Comparison conditions

http://xlibrary.skillport.com/courseware/cbtlib/67002/68153/eng/thin/transcript.html

5/11/2007

SkillSoft Learning Object


You can use the ALTER TABLE command to
l l l l

Page 6 of 10

add constraints drop constraints disable constraints enable constraints

add constraints To add a constraint to a table, you use the ALTER TABLE command followed by an ADD CONSTRAINT clause in which you define the constraint. The following code adds a UNIQUE constraint named comm_emp_id_uk to the commission table. ALTER TABLE commission ADD CONSTRAINT comm_emp_id_uk UNIQUE(emp_id); drop constraints To drop a constraint from a table, you use the ALTER TABLE command with a DROP clause, using the following syntax. When you drop a constraint, Oracle no longer enforces it and the constraint is removed from the data dictionary. ALTER TABLE table DROP PRIMARY KEY | UNIQUE (column) | CONSTRAINT constraint [CASCADE]; The following code drops the UNIQUE constraint comm_emp_id_uk from the commission table. ALTER TABLE commission DROP CONSTRAINT comm_emp_id_uk; The following code drops the PRIMARY KEY constraint from the commission table. To ensure that Oracle no longer enforces any FOREIGN KEY constraints associated with the dropped primary key, you include the CASCADE keyword. ALTER TABLE commission DROP PRIMARY KEY CASCADE; Table altered. disable constraints If you don't want Oracle to enforce a constraint but you do not wish to drop the constraint, you can deactivate the constraint by using the DISABLE clause in an ALTER TABLE statement. You can also use the DISABLE clause in a CREATE TABLE statement if you do not want to enforce a constraint immediately after creating a table. The code for this is: ALTER TABLE table DISABLE CONSTRAINT constraint[CASCADE]; The following code disables the UNIQUE key constraint comm_sales_code_uk in the commission table. ALTER TABLE commission DISABLE CONSTRAINT comm_sales_code_uk;

http://xlibrary.skillport.com/courseware/cbtlib/67002/68153/eng/thin/transcript.html

5/11/2007

SkillSoft Learning Object

Page 7 of 10

If you disable a primary key constraint, you need to include the CASCADE keyword to disable dependent foreign key constraints as well, as shown here. ALTER TABLE security DISABLE CONSTRAINT sec_password_pk CASCADE; enable constraints To activate a disabled constraint, you use the ALTER TABLE statement with an ENABLE clause, using the following syntax. You can also use the ENABLE clause in a CREATE TABLE statement, although this is usually unnecessary because you can enable a constraint in a new table by default. ALTER TABLE table ENABLE CONSTRAINT constraint; When you enable a UNIQUE or PRIMARY KEY constraint, Oracle automatically creates a UNIQUE or PRIMARY KEY index. When you enable a PRIMARY KEY constraint that was previously disabled, Oracle does not enable any FOREIGN KEY constraints that are dependent on the PRIMARY KEY constraint. The following code enables the PRIMARY KEY constraint sec_password_pk in the security table. ALTER TABLE security ENABLE CONSTRAINT sec_password_pk;

Question

What constraints can you define at table level? Options: 1. 2. 3. 4. 5. CHECK FOREIGN KEY NOT NULL PRIMARY KEY UNIQUE

Answer

You can define CHECK, FOREIGN KEY, PRIMARY KEY, and UNIQUE constraints at the table level. Option 1 is correct. A CHECK constraint specifies a condition that must be true for all values in a column. You can define CHECK constraints at either the column or table level. Option 2 is correct. A foreign key is a column or set of columns in one table that

http://xlibrary.skillport.com/courseware/cbtlib/67002/68153/eng/thin/transcript.html

5/11/2007

SkillSoft Learning Object

Page 8 of 10

references a primary or unique key in a second table. You can define FOREIGN KEY constraints at either the column or table level, but you can only define multicolumn FOREIGN KEY constraints at the table level. Option 3 is incorrect. A NOT NULL constraint specifies that a column cannot contain null values. You can define a NOT NULL constraint at column level only. Option 4 is correct. A PRIMARY KEY constraint enforces both a UNIQUE and a NOT NULL constraint on a column or group of columns. You can define PRIMARY KEY constraints at either the column or table level, but you can only define multi-column PRIMARY KEY constraints at the table level. Option 5 is correct. A column with a UNIQUE constraint ensures that each value in a column must be unique. However, null values are allowed. You can only define a composite UNIQUE constraint at the table level.

4. Cascading constraints
Oracle generates an error message if you try to drop a column that is a primary key, part of a multicolumn constraint, or referenced by a foreign key. For example, suppose that you create a table in which the column named pk is the primary key and the column named col1 is referenced by the multicolumn CHECK constraint ck1.

CREATE TABLE sample( pk NUMBER PRIMARY KEY, fk NUMBER CONSTRAINT fk_con REFERENCES sample, col1 NUMBER, CONSTRAINT ck1 CHECK (pk>0 and col1>0));

If you try to drop the pk and col1 columns, Oracle generates the following error messages.

ALTER TABLE sample DROP (pk); DROP (pk) * ERROR at line 2: ORA-12992: cannot drop parent key column ALTER TABLE sample DROP(col1); DROP(col1) * ERROR at line 2: ORA-12991: column is referenced in a multi-column constraint

To drop columns that are specified in constraints, you use the CASCADE CONSTRAINTS clause with the DROP COLUMN clause. The CASCADE CONSTRAINTS clause instructs Oracle to drop all

http://xlibrary.skillport.com/courseware/cbtlib/67002/68153/eng/thin/transcript.html

5/11/2007

SkillSoft Learning Object


l

Page 9 of 10

referential constraints that refer to primary or unique keys that are defined on the dropped columns multicolumn constraints that are defined on the dropped columns

The following code successfully drops the pk and col1 columns.

ALTER TABLE sample DROP(pk,col1) CASCADE CONSTRAINTS;

5. Viewing constraints and associated columns


If you use the DESCRIBE command to view a table, Oracle lists only the NOT NULL constraints on the table.

DESCRIBE employees;

To view all the constraints on a table, you query the data dictionary view USER_CONSTRAINTS. The code for this is:

SELECT constraint_name, constraint_type, search_condition FROM USER_CONSTRAINTS WHERE table_name='EMPLOYEES';

In column C, the output indicates the constraint type as follows:


l l l l

C indicates a CHECK or NOT NULL constraint P indicates a PRIMARY KEY constraint R indicates a referential or FOREIGN KEY constraint U indicates a UNIQUE constraint

To view the columns associated with constraints on a table, you query the USER_CONS_COLUMNS view.

SELECT constraint_name, column_name FROM USER_CONS_COLUMNS WHERE table_name='EMPLOYEES';

This view is useful for identifying the columns associated with constraints that have system-assigned names.

Summary

http://xlibrary.skillport.com/courseware/cbtlib/67002/68153/eng/thin/transcript.html

5/11/2007

SkillSoft Learning Object

Page 10 of 10

In Oracle, you use constraints to prevent the entry of invalid data into tables. You usually create constraints when you create a table. You can define constraints at both table level and column level. You use constraints to specify that a column cannot contain null values, to identify primary and unique keys for a table, to impose conditions on values in columns, and to establish relationships between tables. Once you have created a table with constraints, you can add, drop, disable, and enable constraints by using the ALTER TABLE command with the ADD, DROP, DISABLE, or ENABLE clauses. If you need to drop columns on which constraints are defined, you include the CASCADE CONSTRAINTS clause in the DROP command to drop the associated constraints as well. To view all the constraints on a table, you query the USER_CONSTRAINTS data dictionary view. To view the columns associated with constraints, you query the USER_CONS_COLUMNS view.

Table of Contents
| Top of page | | Learning objective | | 1. Defining constraints | | 2. Constraint types | | 3. Comparison conditions | | 4. Cascading constraints | | 5. Viewing constraints and associated columns | | Summary |

Copyright 2004 SkillSoft. All rights reserved. SkillSoft and the SkillSoft logo are trademarks or registered trademarks of SkillSoft in the United States and certain other countries. All other logos or trademarks are the property of their respective owners.

http://xlibrary.skillport.com/courseware/cbtlib/67002/68153/eng/thin/transcript.html

5/11/2007

Das könnte Ihnen auch gefallen