Constraint
Constraint
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.
A primary key constraint that is defined using only one column of a table in the
database is called Simple 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.
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.
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
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.
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
Let’s again take the above example and see how we can define the primary key
constraint promstr_col1_pid_pk at table level:
Please watch the video tutorial on the same topic for line by line explanation of
the above code.
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:
That is how we use ALTER TABLE statement to add a primary key constraint in
an already created table.
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.
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.
So let’s modify the primary key constraint and see how to enable or disable it
using the name of the constraint.
For example let’s say you want to disable cust_cid_pk constraint which we
earlier defined on the Customer table.
USER_CONSTRAINTS
USER_CONS_COLUMNS
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’;
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.
Similar to primary key constraint Foreign Key constraint is also of two types:
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.
There are a few things which you should know about the foreign key (Features
of Foreign Key):
You can define foreign key constraint either by using CREATE TABLE statement
or by using ALTER TABLE
statement.
This way of defining constraint is called column level because we define the
constraint with column definition while creating table.
Syntax
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.
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.
To demonstrate how to define foreign key using create table at table level I’ll
recreate our child table called BOOKS.
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.
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.
For Example:
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)
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.
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.
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.
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.
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.
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!
=====================================================================================
=====================================================================================
· 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.
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.
GO
Note we changed the check constraint to check for specific value that
doesn’t depend on any other column on the table.
CONSTRAINT clause
a table-level constraint
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
FOREIGN KEY
CHECK
PRIMARY KEY
Specifies the column or columns that uniquely identify a row in the table.
NULL values are not allowed.
UNIQUE
FOREIGN KEY
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
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.
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.
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 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.
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.
The search condition must always return the same value if applied to the same
values. Thus, it cannot contain any of the following:
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.
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:
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)
);