Sunteți pe pagina 1din 30

How to Define Primary Key Constraint

Whenever we talk about database constraint the first thing which comes into
our mind is the primary key constraint. So today in this tutorial we will see what
is a Primary key constraint and the different ways of defining it on a table.

Definition
Primary key constraint is an Input/output Data constraint which serves
the purpose of uniquely identifying the rows in a table.

What is a Primary Key Constraint?


Primary key constraint is the combination of NOT NULL and UNIQUE constraints.
In a more proper manner you can define a primary key constraint as an
Input/output Data constraint which serves the purpose of uniquely identifying
the rows in a table.

Types of Primary Keys


There are two types of Primary keys:

1. Simple Primary Key and


2. Composite Primary Key.

Simple Primary Key

A primary key constraint that is defined using only one column of a table in the
database is called Simple Primary Key Constraint.

Composite Primary Key


A primary key constraint that is defined using more than one column of a table
in the database is called Composite Primary key constraint.

Primary key has a single function of identifying a unique row in the table. In
case the simple primary key fails to identify that unique row, the user must
then define a composite primary key. There are some restrictions on composite
primary key, for example a composite primary key can be defined using up to
32 columns of a table in oracle database.

Quick Tip
How to ensure the uniqueness of a primary key constraint?
Oracle automatically creates a unique index so that the requirement of
the uniqueness of the PRIMARY KEY constraint is fulfilled.

How to Create a Primary Key Constraint in


Oracle Database
Primary key constraint can be defined in two ways:

1. Using CREATE TABLE statement and


2. Using ALTER TABLE statement

You can define a primary key constraint either during the creation of a table
using CREATE TABLE statement or after creating a table using ALTER TABLE
statement.

If you choose to define a primary key using CREATE TABLE statement then you
have two different levels at which you have to define a primary key.

1. At Column Level
2. At Table Level.
Let’s learn all
about the above mentioned ways of defining a Primary Key constraint one by
one.

Defining Primary Key Using CREATE TABLE


As mentioned above we can define a primary key in two ways using create
table. Let’s start with the first way which is Defining Primary key at Column
Level.

Define Primary key at Column Level

In the create table statement you define any column as a primary key column
just by putting reserved phrase “Primary key” right after defining the column.
This means you have to put reserved phrase “Primary Key” after data type and
size in column definition. For example

Example 1: Primary Key at Column Level

CREATE TABLE product_master


(
Product_id NUMBER(3) PRIMARY KEY,
Product_name VARCHAR2(30),
Product_price NUMBER(5)
);

As you can see in the above code the column product_id is a primary key
column. But it is always a good practice to give a unique and meaningful name
to your primary key constraint every time you create it. This will make the
managing of your constraint much easier.

How to Name Your Constraint in Oracle


Database?
In case you do not provide a meaningful name to your constraint then the
oracle database server gives it a default name automatically. If you have
several constraints on your table then using this default name makes it very
difficult to find a specific constraint.

You can use keyword “CONSTRAINT” to give your constraint a meaningful


name. Let’s modify the above code and give our constraint a name.

Example 2: How to name a primary key constraint

CREATE TABLE product_master


(

Product_id NUMBER(3) CONSTRAINT promstr_col1_pid_pk PRIMA


RY KEY,
Product_name VARCHAR2(30),
Product_price NUMBER(5)
);

That is how we define a primary key constraint at column level using Create
Table Statement in Oracle database. Now let’s see the second way of creating a
primary key.
Define Primary key at Table Level

Defining the primary key constraint at table level is one of my favorite ways as
it helps me to manage all my constraints specially when dealing with a huge line
of code.

Defining a constraint at table level separates the column definition from the
constraint definition. In this way you first define all the columns of a table and
then you define all your constraints in the Create Table Statement. For Example

Example 3: Primary Key Constraint at Table Level

Let’s again take the above example and see how we can define the primary key
constraint promstr_col1_pid_pk at table level:

CREATE TABLE product_master


(
Product_id NUMBER(3),
Product_name VARCHAR2(30),
Product_price NUMBER(5),
CONSTRAINT promstr_col1_pid_pk PRIMARY KEY (product_id)
);

Please watch the video tutorial on the same topic for line by line explanation of
the above code.

How to Define Primary Key Using ALTER


TABLE statement?
You can use ALTER TABLE statement to add the constraint in an already created
table or to change the definition of already defined constraint in the table.

Example 4:
Let’s say we have a table “Customer” with 3 columns Cust_id, cust_name,
phone_no and we don’t have any Primary Key constraint on any column and
now we want to add Primary Key constraint on cust_id column. To do this we
can use ALTER TABLE statement:

ALTER TABLE customer ADD CONSTRAINT cust_cid_pk PRIMARY KE


Y (cust_id);

That is how we use ALTER TABLE statement to add a primary key constraint in
an already created table.

How to Define a Composite Primary Key Constraint?

As said above that the primary key defined using more than one column is
called a composite primary key. Let’s see how to define a composite primary
key.

Example 5: Composite Primary Key

CREATE TABLE customer


(
cust_id NUMBER(3),
cust_name VARCHAR2(3),
phone_no NUMBER(10),
CONSTRAINT cust_cid_pk PRIMARY KEY ( cust_id, phone_no)
);

In the above code we create a table with the name ‘Customer’ which has 3
columns. The primary key constraint is defined using two columns cust_id and
phone_no.

Example 6: Composite Primary Key Using ALTER TABLE


Similar to simple primary key you can add a composite primary key to an
already created table using ALTER TABLE statement.

ALTER TABLE customer ADD CONSTRAINT cust_cid_pk PRIMARY KEY


(cust_id,phone_number);

How To Enable and Disable a Primary Key


Constraint?
If you were wondering what is the requirement of giving a name to a constraint
then here is the answer. Modifying a constraint becomes easier if your
constraint has a unique and meaningful name. If you do not provide a name to
your constraint then oracle server gives a default name to it which is quite
generic and it becomes difficult to find a specific constraint using that name.

So let’s modify the primary key constraint and see how to enable or disable it
using the name of the constraint.

Example 7: Enable or Disable primary key

For example let’s say you want to disable cust_cid_pk constraint which we
earlier defined on the Customer table.

Disable Primary key constraint

ALTER TABLE customer DISABLE CONSTRAINT cust_cid_pk;

If you want to enable this constraint then simply write

Enable Primary key constraint

ALTER TABLE customer ENABLE CONSTRAINT cust_cid_pk;


How to Check Constraint on a Table
As we know that DESC statement shows nothing about constraints on a table.
But Oracle Database provides us several DATA DICTIONARIES for checking or
describing all the constraints which we have defined on our table.

These Data Dictionaries are:

 USER_CONSTRAINTS
 USER_CONS_COLUMNS

Here USER_CONSTRAINTS gives a brief about the constraint on a table.


USER_CONS_COLUMNS is a Data Dictionary which holds detailed information
about columns of a table. Let’s see how to use them to get information about
the primary key constraint.

For example let’s say you want to see constraint details on customer table

USER_CONSTRAINTS

SELECT
CONSTRAINT_NAME,
CONSTRAINT_TYPE,
TABLE_NAME,
STATUS,
INDEX_NAME
FROM user_CONSTRAINTS WHERE table_name = ‘CUSTOMER’;

USER_CONS_COLUMNS

SELECT
CONSTRAINT_NAME,
TABLE_NAME,
COLUMN_NAME,
POSITION
FROM user_cons_columns WHERE table_name = ‘CUSTOMER’;

Restrictions on a primary key constraint


1. You cannot delete a Primary key if it is referenced by a foreign key in
some other table.
2. A table can have only One Primary key no matter whether it’s Simple
Primary Key Or Composite Primary Key.
3. Columns which are participating in Primary Key cannot have NULL
values. This means you cannot leave them unattended or you cannot
put NULL value into them.
4. As primary key is all about row or record’s uniqueness thus it will not
allow duplicate values.
5. When a Primary Key constraint has been defined on multiple columns
then its values can be duplicated provided the duplication is happening
within one single column. However the combination of values of all the
columns defining each primary key constraint should be unique.
6. Data-types such as LOB, LONG, LONG RAW, VARRAY, NESTED TABLE,
BFILE, REF, TIMESTAMP WITH TIME ZONE, or user-defined type are
not allowed with the columns which are part of Primary key. Any
attempt of creating a primary key with the column of these data-types
will raise SQL Error: ORA-02269.
7. The size of the primary key cannot exceed approximately one database
block.
8. As I have already mentioned above that a composite primary key can
have maximum of 32 columns.
9. The Primary Key and Unique Key should never be designated as the
same column or combination of columns.
10. You cannot specify a primary key when creating a sub view in an
inheritance hierarchy. The primary key can be specified only for the
top-level (root) view.
11. Unique cluster Index gets created automatically at the time of
creating Primary key.
12. Although it is not necessary for you to define a primary key yet it is
always recommended to do so.

So that’s all about PRIMARY KEY. Hope it gives you a detailed insight into the
concept. You can visit my YouTube channel for tutorials on Primary Key. Do like
and Subscribe to my videos. Thanks for reading & have a great day!

=====================================================================================
=====================================================================================

In the last tutorial we learnt about Primary key constraint and today I would like
to elaborate on another topic in Oracle database that is referential integrity
constraint or Foreign Key.

Definition
Foreign key is an Input/output data constraint which is also known as referential
integrity constraint. Foreign key represents a link or say a relationship between
columns of tables.

Types Of Foreign Key Constraint

Similar to primary key constraint Foreign Key constraint is also of two types:

1. Simple Foreign key constraint and


2. Composite Foreign key constraint.

What Are Simple & Composite Foreign Key Constraints?


Constraint which involves only one column in foreign key in child table and one
column in reference key in parent table is called Simple Foreign Key.

While the constraint which involves more than one column in foreign key in the
child table as well as more than one column in reference key in the parent table
is called Composite Foreign Key.

Features of Foreign Key

There are a few things which you should know about the foreign key (Features
of Foreign Key):

1. You cannot define a foreign key constraint in a CREATE TABLE


statement that contains an AS sub query clause. Instead, you must
create the table without the constraint and then add it later with an
ALTER TABLE statement.
2. None of the columns in the foreign key can be of LOB, LONG, LONG
RAW, VARRAY, NESTED TABLE, BFILE, REF, TIMESTAMP WITH TIME
ZONE, or user-defined type. However, the primary key can contain a
column of TIMESTAMP WITH LOCAL TIME ZONE.
3. A composite foreign key cannot have more than 32 columns.
4. Referenced key in parent table must either be a Primary Key or a
Unique Key.
5. Records in parent table cannot be updated if child record exists.
6. Foreign Key Constraint can be specified only on child table and not on
parent table.

Tables Of Foreign Key Constraint


Foreign key involves two different tables. First one is PARENT TABLE or
referenced Table and the second one is CHILD TABLE or foreign table.
1. The column of parent table which will get referenced by foreign key
must be either Primary Key or Unique Key.
2. Column(s) in child table can contain NULL or Duplicate values while the
vice versa is not true.
3. Column(s) of parent table & column(s) of child table which are
participating in foreign key should be of the same data-type and size
(column width).

How to create/ Define Foreign key

You can define foreign key constraint either by using CREATE TABLE statement
or by using ALTER TABLE

statement.

1. Defining Foreign Key Using Create table at Column Level

This way of defining constraint is called column level because we define the
constraint with column definition while creating table.

Syntax

Column_name Datatype(size) REFERENCES


parent_table_name (parent_column_name)
For example

To demonstrate this we will use two tables – parent table with the name
of Authors and child table with the name of Books. Parent table ‘authors’ is a
simple table with 2 columns Author_id and Author_name where Author_id is a
Primary key column. You can add as many columns as you want.

Read how to create table and how to define primary key on a table.

CREATE TABLE author


(
author_id NUMBER(3) CONSTRAINT athr_aid_pk PRIMARY
KEY,
author_name VARCHAR2(30)
);

Now let’s create our child table ‘BOOKS’. The structure of this table contains
various columns – book_id which will be the primary key for this table,
book_title, book_price and book_author_id. The 4th column will be the foreign
key which will reference the author_id column of author table. You can give
whatever name to this column but data-type and the size (column width) must
be the same as that of author_id column in author table.

CREATE TABLE books


(
book_id NUMBER(3),
book_title VARCHAR2(30),
book_price NUMBER(3),
book_author_id NUMBER(3) CONSTRAINT bok_ai_fk
REFERENCES author(author_id)
);

2. How to define foreign key using CREATE TABLE at table Level


In order to define foreign key Using create table at table level you have to
define all the columns of your child table first. Then you have to define foreign
key at the end of the table.
Let’s see the syntax first –

CONSTRAINT constraint_name FOREIGN


KEY(child_table_column) REFERENCES
Parent_table_name(parent_table_column)

To demonstrate how to define foreign key using create table at table level I’ll
recreate our child table called BOOKS.

CREATE TABLE books


(
book_id NUMBER(3) CONSTRAINT bok_bi_pk PRIMARY KEY,
book_title VARCHAR2(30),
book_price NUMBER(3),
book_author_id NUMBER(3),
CONSTRAINT bok_ai_fk FOREIGN KEY (book_author_id)
REFERENCES author(author_id)
);

As you can see I defined all the columns first and then in the last statement of
Create table I defined the foreign Key constraint.

Define Foreign Key Using ALTER TABLE statement

We define Foreign Key through ALTER TABLE statement in the scenario when
we already have a table and want to emphasize the constraint over it.

Suppose we have a simple table with primary key by the name of BOOKS
[Please watch my tutorial on How to create table to learn all about it] and now
we want to emphasize the FOREIGN KEY constraint on this table. In this case
we will use ALTER TABLE statement.

Let’s see how

First let’s go through the syntax –

ALTER TABLE child_table_name ADD FOREIGN KEY


(child_column) REFERENCES parent_table_name(parent_column)

For Example:

ALTER TABLE books ADD CONSTRAINT bok_ai_fk FOREIGN KEY


(book_author_id) REFERENCES author(author_id);

If you try to delete a parent table which has a primary or a unique key
referenced by child table then oracle will give you a SQL Error: ORA-02449.
However if you want then you can still drop the child table without any error.

So there you are! This is all about the foreign key concept. Please remember
that there are many small topics that branch out from this main foreign key
concept and are beyond the scope of this article. Nevertheless hope you liked it.
Please share this blog on Foreign Key in Oracle Database with your friends and
colleagues.

You can also visit my YouTube channel for the video tutorial explaining foreign
key concept. Thanks & have a great day!

=====================================================================================
=====================================================================================

The Previous tutorial was all about foreign key constraint in Oracle Database.
There we learnt that the foreign key constraint establishes a link / relation
between PARENT and CHILD table.
The foreign key is defined in the child table and the parent table contains the
reference column. However because of this link we
cannot update or delete the rows of the parent table.

Activity
Go To my previous tutorial on foreign key and create parent (authors)
and child (books) table with foreign key and after creating them try to
drop the parent (authors) table and see what will happen.
(To drop parent table AUTHORS execute DROP TABLE AUTHORS; ddl)

Read How To Define Foreign Key

So, what is special about foreign key which won’t let us


Delete or Update the records of the parent table?

When you define a simple foreign key, the Oracle engine is by default set to ON
DELETE NO ACTION clause. This means that you are allowed to update the
rows in the parent table however you cannot delete rows from the parent table.
This default behavior is called Restrict rule. This rule doesn’t allow users to
delete or update reference data in the parent table.

Does that mean we cannot update or delete the records of


parent table if we have a foreign key constraint defined on
it?

Definitely not. You can easily override this restrict rule and change the default
behavior of the foreign key either to SET NULL or to DELETE CASCADE.

That’s the beauty of working with Oracle Database, you always get the solutions
to the problems.

So how can we change the default behavior of foreign key?


In Oracle Database you get two referential actions to override the restrict rule
and change the default behavior of foreign key. These two referential actions
are –

1. ON DELETE SET NULL and


2. ON DELETE CASCADE

In this tutorial we will concentrate on the first referential action which is On


Delete Set Null and see how we can change the default behavior which is ON
DELETE NO ACTION of the foreign key in Oracle Database.

What is ON DELETE SET NULL clause of the foreign key


constraint?

On Delete Set Null clause sets all the records of the column which is defined as
a foreign key in the child table to Null if the corresponding record in the parent
table is deleted.

Can you demonstrate us how to define an “On Delete Set


Null” clause with foreign key?

Sure, why not let’s do an example demonstrating the On Delete Set Null clause
with foreign key in Oracle Database. For the demonstration we will be using the
same tables which we created in the previous tutorial.

Let’s first create the parent table which will hold the reference column of our
foreign key. The name of the table will be Author and there will be two columns
in this table author_id and author_name. The first column which is author_id
will serve as the reference column for the foreign key.

CREATE TABLE author


( author_id NUMBER(3) CONSTRAINT athr_aid_pk
PRIMARY KEY, author_name VARCHAR2(30) );
We specify the clause On Delete Set Null along with the definition of foreign key
and as mentioned above, we define a foreign key in the child table. Thus now
we need a child table.

CREATE TABLE books


(
book_id NUMBER(3),
book_title VARCHAR2(30),
book_price NUMBER(3),
book_author_id NUMBER(3) CONSTRAINT bok_ai_fk
REFERENCES author(author_id) ON DELETE SET NULL
);

Here we have our child table. In this table the column book_author_id will serve
as the foreign key. If you will see the foreign key definition of this column then
you will notice that at the end of the foreign key definition we specified our
clause which is “On Delete Set Null”.

This is how you define a foreign key with ON DELETE SET NULL with create
table in column level.

Is there any way to confirm that the foreign key is defined


with on delete set null clause this time?

Yes, you can check this constraint by executing the query on


– USER_CONSTRAINTS data dictionary.

SELECT
constraint_name, delete_rule
FROM user_constraints
WHERE table_name = ‘BOOKS’ ;
So guys, this is the process by which you can change Oracle’s default behavior
to ON DELETE SET NULL clause using foreign key. Hope you find this blog
useful.

Do read my next article explaining ON DELETE CASCADE clause. You can also
watch my YouTube tutorial on the same. Please do like, share and subscribe!
Thanks & have a great day!

=====================================================================================
=====================================================================================

Table Level VS Column Level Constraints


Table Level VS Column Level Constraints:
In this article we will differentiate between column level constraints and row
level constraints.
Constraint is a way of enforcing rules in the database, and it maintains the
integrity of the database.

There are many types of constraints:


(More information: http://msdn.microsoft.com/en-us/library/ms189862%28v=sql.105%29.aspx )

· Primary key.
· Foreign key.

· Not null.

· Check.

· Unique.
· Default constraints.

The syntax of each constraint is really obvious but how to use it and where
it applicable or not.
And we may divide constraint into:
1. Table Level Constraints.

In this type the constraint is checked if there is any modification to a


row, regardless the value of the column changed or not.

One good example of this type is the check constraint, if we create


check constraint in table level the constraint will be checked each
time the row has been affected by any type of change.
CREATE TABLE [TABLELEVEL]

[ID] INT PRIMARY KEY,

[STARTDATE] DATE NOT NULL,

[ENDDATE] DATE NOT NULL,

[CHECKED] DATE NOT NULL,

CONSTRAINT TABLELEVELCONSTRIANT CHECK( [CHECKED] BETWEEN [STARTDATE] AND [ENDDATE])

GO

As you see in the above code the checked column has check
constraint to check if it between startdate and enddate, either the
value of the checked column modified or any other column is
modified (startdate, enddate, ..) the check constraint will be evaluated.
The primary key constraint always evaluate if any value in the whole
table (not on the column or row) is changed if we have composite
primary key we need to check all columns to check if it meet the
constraint or not and the new added or modified value does not
make any conflict with other row.

2. Column Level Constraints.


In this type the constraint is checked when the value of the column
changed.

If we consider the previous example of check constraint a little


change to the code definition will make the constraint be checked on
the column not on the row.
CREATE TABLE [COLUMNLEVEL]

[ID] INT PRIMARY KEY,

[STARTDATE] DATE NOT NULL,

[ENDDATE] DATE NOT NULL,

[CHECKED] DATE NOT NULL,

CONSTRAINT COLUMNLEVELCONSTRIANT CHECK( [CHECKED] > '2012-01-01')

GO

Note we changed the check constraint to check for specific value that
doesn’t depend on any other column on the table.

To sum up if the constraint depends on other column or we need to


check other column(s) or rows this constraint will be table level
constraint.
=====================================================================================
=====================================================================================

CONSTRAINT clause

A CONSTRAINT clause is an optional part of a CREATE TABLE


statement or ALTER TABLE statement. A constraint is a rule to which data must
conform. Constraint names are optional.

A CONSTRAINT can be one of the following:


 a column-level constraint

Column-level constraints refer to a single column in the table and do not


specify a column name (except check constraints). They refer to the column
that they follow.

 a table-level constraint

Table-level constraints refer to one or more columns in the table. Table-level


constraints specify the names of the columns to which they apply. Table-level
CHECK constraints can refer to 0 or more columns in the table.

Column constraints include:

 NOT NULL

Specifies that this column cannot hold NULL values (constraints of this type
are not nameable).

 PRIMARY KEY

Specifies the column that uniquely identifies a row in the table. The identified
columns must be defined as NOT NULL.

Note: If you attempt to add a primary key using ALTER TABLE and any of the
columns included in the primary key contain null values, an error will be
generated and the primary key will not be added. See ALTER TABLE
statement for more information.

 UNIQUE

Specifies that values in the column must be unique.

 FOREIGN KEY

Specifies that the values in the column must correspond to values in a


referenced primary key or unique key column or that they are NULL.

 CHECK

Specifies rules for values in the column.


Table constraints include:

 PRIMARY KEY

Specifies the column or columns that uniquely identify a row in the table.
NULL values are not allowed.

 UNIQUE

Specifies that values in the columns must be unique.

 FOREIGN KEY

Specifies that the values in the columns must correspond to values in


referenced primary key or unique columns or that they are NULL.

Note: If the foreign key consists of multiple columns, and any column is NULL,
the whole key is considered NULL. The insert is permitted no matter what is
on the non-null columns.

 CHECK

Specifies a wide range of rules for values in the table.

Column constraints and table constraints have the same function; the difference is in
where you specify them. Table constraints allow you to specify more than one column
in a PRIMARY KEY, UNIQUE, CHECK, or FOREIGN KEY constraint definition.
Column-level constraints (except for check constraints) refer to only one column.

A constraint operates with the privileges of the owner of the constraint. See "Using
SQL standard authorization" and "Privileges on views, triggers, and constraints" in
the Java DB Developer's Guide for details.

Syntax
Primary key constraints
A primary key defines the set of columns that uniquely identifies rows in a table.

When you create a primary key constraint, none of the columns included in the
primary key can have NULL constraints; that is, they must not permit NULL values.
ALTER TABLE ADD PRIMARY KEY allows you to include existing columns in a
primary key if they were first defined as NOT NULL. NULL values are not allowed.
If the column(s) contain NULL values, the system will not add the primary key
constraint. See ALTER TABLE statement for more information.

A table can have at most one PRIMARY KEY constraint.

Unique constraints
A UNIQUE constraint defines a set of columns that uniquely identify rows in a table
only if all the key values are not NULL. If one or more key parts are NULL, duplicate
keys are allowed.

For example, if there is a UNIQUE constraint on col1 and col2 of a table, the
combination of the values held by col1 and col2 will be unique as long as these
values are not NULL. If one of col1 and col2 holds a NULL value, there can be
another identical row in the table.

A table can have multiple UNIQUE constraints.

Foreign key constraints


Foreign keys provide a way to enforce the referential integrity of a database. A
foreign key is a column or group of columns within a table that references a key in
some other table (or sometimes, though rarely, the same table). The foreign key must
always include the columns of which the types exactly match those in the referenced
primary key or unique constraint.

For a table-level foreign key constraint in which you specify the columns in the table
that make up the constraint, you cannot use the same column more than once.

If there is a column list in the ReferencesSpecification (a list of columns in the


referenced table), it must correspond either to a unique constraint or to a primary key
constraint in the referenced table. The ReferencesSpecification can omit the column
list for the referenced table if that table has a declared primary key.

If there is no column list in the ReferencesSpecification and the referenced table has
no primary key, a statement exception is thrown. (This means that if the referenced
table has only unique keys, you must include a column list in
the ReferencesSpecification.)
A foreign key constraint is satisfied if there is a matching value in the referenced
unique or primary key column. If the foreign key consists of multiple columns, the
foreign key value is considered NULL if any of its columns contains a NULL.
Note: It is possible for a foreign key consisting of multiple columns to allow one of
the columns to contain a value for which there is no matching value in the
referenced columns, per the SQL-92 standard. To avoid this situation, create NOT
NULL constraints on all of the foreign key's columns.

Foreign key constraints and DML


When you insert into or update a table with an enabled foreign key
constraint, Derby checks that the row does not violate the foreign key constraint by
looking up the corresponding referenced key in the referenced table. If the constraint
is not satisfied, Derby rejects the insert or update with a statement exception.

When you update or delete a row in a table with a referenced key (a primary or unique
constraint referenced by a foreign key), Derby checks every foreign key constraint
that references the key to make sure that the removal or modification of the row does
not cause a constraint violation. If removal or modification of the row would cause a
constraint violation, the update or delete is not permitted and Derby throws a
statement exception.

Derby performs constraint checks at the time the statement is executed, not when the
transaction commits.

Backing indexes
UNIQUE, PRIMARY KEY, and FOREIGN KEY constraints generate indexes that
enforce or "back" the constraint (and are sometimes called backing indexes).
PRIMARY KEY constraints generate unique indexes. FOREIGN KEY constraints
generate non-unique indexes. UNIQUE constraints generate unique indexes if all the
columns are non-nullable, and they generate non-unique indexes if one or more
columns are nullable. Therefore, if a column or set of columns has a UNIQUE,
PRIMARY KEY, or FOREIGN KEY constraint on it, you do not need to create an
index on those columns for performance. Derby has already created it for you.
See Indexes and constraints.

These indexes are available to the optimizer for query optimization (see CREATE
INDEX statement) and have system-generated names.
You cannot drop backing indexes with a DROP INDEX statement; you must drop the
constraint or the table.

Check constraints
A check constraint can be used to specify a wide range of rules for the contents of a
table. A search condition (which is a boolean expression) is specified for a check
constraint. This search condition must be satisfied for all rows in the table. The search
condition is applied to each row that is modified on an INSERT or UPDATE at the
time of the row modification. The entire statement is aborted if any check constraint is
violated.

Requirements for search condition


If a check constraint is specified as part of a column-definition, a column reference
can only be made to the same column. Check constraints specified as part of a table
definition can have column references identifying columns previously defined in the
CREATE TABLE statement.

The search condition must always return the same value if applied to the same
values. Thus, it cannot contain any of the following:

 Dynamic parameters (?)


 Date/Time Functions (CURRENT_DATE, CURRENT_TIME,
CURRENT_TIMESTAMP)
 Subqueries
 User Functions (such as USER, SESSION_USER, CURRENT_USER)

Referential actions
You can specify an ON DELETE clause and/or an ON UPDATE clause, followed by
the appropriate action (CASCADE, RESTRICT, SET NULL, or NO ACTION) when
defining foreign keys. These clauses specify whether Derbyshould modify
corresponding foreign key values or disallow the operation, to keep foreign key
relationships intact when a primary key value is updated or deleted from a table.

You specify the update and delete rule of a referential constraint when you define the
referential constraint.

The update rule applies when a row of either the parent or dependent table is updated.
The choices are NO ACTION and RESTRICT.
When a value in a column of the parent table's primary key is updated and the update
rule has been specified as RESTRICT, Derby checks dependent tables for foreign key
constraints. If any row in a dependent table violates a foreign key constraint, the
transaction is rolled back.

If the update rule is NO ACTION, Derby checks the dependent tables for foreign key
constraints after all updates have been executed but before triggers have been
executed. If any row in a dependent table violates a foreign key constraint, the
statement is rejected.

When a value in a column of the dependent table is updated, and that value is part of a
foreign key, NO ACTION is the implicit update rule. NO ACTION means that if a
foreign key is updated with a non-null value, the update value must match a value in
the parent table's primary key when the update statement is completed. If the update
does not match a value in the parent table's primary key, the statement is rejected.

The delete rule applies when a row of the parent table is deleted and that row has
dependents in the dependent table of the referential constraint. If rows of the
dependent table are deleted, the delete operation on the parent table is said to
be propagated to the dependent table. If the dependent table is also a parent table, the
action specified applies, in turn, to its dependents.

The choices are NO ACTION, RESTRICT, CASCADE, or SET NULL. SET NULL
can be specified only if some column of the foreign key allows null values.

If the delete rule is:

NO ACTION, Derby checks the dependent tables for foreign key constraints after all
deletes have been executed but before triggers have been executed. If any row in a
dependent table violates a foreign key constraint, the statement is rejected.

RESTRICT, Derby checks dependent tables for foreign key constraints. If any row in
a dependent table violates a foreign key constraint, the transaction is rolled back.

CASCADE, the delete operation is propagated to the dependent table (and that table's
dependents, if applicable).

SET NULL, each nullable column of the dependent table's foreign key is set to null.
(Again, if the dependent table also has dependent tables, nullable columns in those
tables' foreign keys are also set to null.)
Each referential constraint in which a table is a parent has its own delete rule; all
applicable delete rules are used to determine the result of a delete operation. Thus, a
row cannot be deleted if it has dependents in a referential constraint with a delete rule
of RESTRICT or NO ACTION. Similarly, a row cannot be deleted if the deletion
cascades to any of its descendants that are dependents in a referential constraint with
the delete rule of RESTRICT or NO ACTION.

Deleting a row from the parent table involves other tables. Any table involved in a
delete operation on the parent table is said to be delete-connected to the parent
table. The delete can affect rows of these tables in the following ways:

 If the delete rule is RESTRICT or NO ACTION, a dependent table is involved in


the operation but is not affected by the operation. (That is, Derby checks the
values within the table, but does not delete any values.)
 If the delete rule is SET NULL, a dependent table's rows can be updated when
a row of the parent table is the object of a delete or propagated delete
operation.
 If the delete rule is CASCADE, a dependent table's rows can be deleted when a
parent table is the object of a delete.
 If the dependent table is also a parent table, the actions described in this list
apply, in turn, to its dependents.

Examples
-- column-level primary key constraint named OUT_TRAY_PK:
CREATE TABLE SAMP.OUT_TRAY
(
SENT TIMESTAMP,
DESTINATION CHAR(8),
SUBJECT CHAR(64) NOT NULL CONSTRAINT OUT_TRAY_PK PRIMARY KEY,
NOTE_TEXT VARCHAR(3000)
);

-- the table-level primary key definition allows you to


-- include two columns in the primary key definition:
CREATE TABLE SAMP.SCHED
(
CLASS_CODE CHAR(7) NOT NULL,
DAY SMALLINT NOT NULL,
STARTING TIME,
ENDING TIME,
PRIMARY KEY (CLASS_CODE, DAY)
);

-- Use a column-level constraint for an arithmetic check


-- Use a table-level constraint
-- to make sure that a employee's taxes does not
-- exceed the bonus
CREATE TABLE SAMP.EMP
(
EMPNO CHAR(6) NOT NULL CONSTRAINT EMP_PK PRIMARY KEY,
FIRSTNME CHAR(12) NOT NULL,
MIDINIT vARCHAR(12) NOT NULL,
LASTNAME VARCHAR(15) NOT NULL,
SALARY DECIMAL(9,2) CONSTRAINT SAL_CK CHECK (SALARY >= 10000),
BONUS DECIMAL(9,2),
TAX DECIMAL(9,2),
CONSTRAINT BONUS_CK CHECK (BONUS > TAX)
);

-- use a check constraint to allow only appropriate


-- abbreviations for the meals
CREATE TABLE FLIGHTS
(
FLIGHT_ID CHAR(6) NOT NULL ,
SEGMENT_NUMBER INTEGER NOT NULL ,
ORIG_AIRPORT CHAR(3),
DEPART_TIME TIME,
DEST_AIRPORT CHAR(3),
ARRIVE_TIME TIME,
MEAL CHAR(1) CONSTRAINT MEAL_CONSTRAINT
CHECK (MEAL IN ('B', 'L', 'D', 'S')),
PRIMARY KEY (FLIGHT_ID, SEGMENT_NUMBER)
);

CREATE TABLE METROPOLITAN


(
HOTEL_ID INT NOT NULL CONSTRAINT HOTELS_PK PRIMARY KEY,
HOTEL_NAME VARCHAR(40) NOT NULL,
CITY_ID INT CONSTRAINT METRO_FK REFERENCES CITIES
);

-- create a table with a table-level primary key constraint


-- and a table-level foreign key constraint
CREATE TABLE FLTAVAIL
(
FLIGHT_ID CHAR(6) NOT NULL,
SEGMENT_NUMBER INT NOT NULL,
FLIGHT_DATE DATE NOT NULL,
ECONOMY_SEATS_TAKEN INT,
BUSINESS_SEATS_TAKEN INT,
FIRSTCLASS_SEATS_TAKEN INT,
CONSTRAINT FLTAVAIL_PK PRIMARY KEY (FLIGHT_ID, SEGMENT_NUMBER),
CONSTRAINT FLTS_FK
FOREIGN KEY (FLIGHT_ID, SEGMENT_NUMBER)
REFERENCES Flights (FLIGHT_ID, SEGMENT_NUMBER)
);
-- add a unique constraint to a column
ALTER TABLE SAMP.PROJECT
ADD CONSTRAINT P_UC UNIQUE (PROJNAME);

-- create a table whose city_id column references the


-- primary key in the Cities table
-- using a column-level foreign key constraint
CREATE TABLE CONDOS
(
CONDO_ID INT NOT NULL CONSTRAINT hotels_PK PRIMARY KEY,
CONDO_NAME VARCHAR(40) NOT NULL,
CITY_ID INT CONSTRAINT city_foreign_key
REFERENCES Cities ON DELETE CASCADE ON UPDATE RESTRICT
);
=====================================================================================
=====================================================================================

S-ar putea să vă placă și