You are on page 1of 31

04/22/20

Integrity Constraints
and
Assertions
IF-2213 Pemrograman Basis Data
Tahun Ajaran 2012-2013

1
04/22/20
Constraints on a Single Relation
CREATE TABLE MovieStar
( name VARCHAR2(30),
birthplace VARCHAR2(50),
gender CHAR(1),
birthdate DATE
);

2
04/22/20
Integrity Constraints
• Integrity constraints guard against accidental damage to the
database, by ensuring that authorized changes to the database do
not result in a loss of data consistency.
– A checking account must have a balance greater than
$10,000.00.
– A salary of a bank employee must be at least $4.00 an hour.
– A customer must have a (non-null) phone number.

3
04/22/20
Constraints on a Single Relation
• not null
• primary key
• unique
• check (P), where P is a predicate

4
04/22/20
Constraints on a Single Relation
• not null
– Declare name to be not null
– Example:
name VARCHAR(20) NOT NULL

• primary key
– Two tuples in R cannot agree on all of the attributes in set S
– Attributes in S are not allowed to have NULL as a value in their
component
– Example:
name VARCHAR(20) PRIMARY KEY
or
PRIMARY KEY (name)

5
04/22/20
Constraints on a Single Relation
• unique ( A1, A2, …, Am)
– The unique specification states that the attributes A1, A2, …
Am cannot agree on all of the attribute
– It also implies that the attributes A1, A2, … Am form a
candidate key. Candidate keys are permitted to be null (in
contrast to primary keys).
– Example:
name VARCHAR(20) UNIQUE
or
UNIQUE (name, birthplace, birthdate)

6
04/22/20
Constraints on a Single Relation
• check (P)
– When a row is inserted or an existing row is modified, the
conditional expression in the CHECK constraint is evaluated
– If it evaluates to false, the command is rejected
– Example: ensure that the gender in MovieStar is either ‘F’ for
female and ‘M’ for male
gender CHAR(1) CHECK (gender IN (‘M’,’F’)),

7
04/22/20
Constraints on a Single Relation
CREATE TABLE MovieStar
( name VARCHAR2(30),
birthplace VARCHAR2(50),
gender CHAR(1) CHECK (gender IN (‘M’,’F’)),
birthdate DATE,
PRIMARY KEY (name),
UNIQUE (name, birthplace, birthdate),
);

8
04/22/20
Constraints on a Single Relation
CREATE TABLE Movie
( title VARCHAR2(50),
year NUMBER(4),
length NUMBER(3),
inColor CHAR(1),
studioName VARCHAR2(30),
PRIMARY KEY (title, year)
);

• The length of a movie cannot be less than 60 nor more than 250
• The incolor option for movie must be ‘N’ for black-and-white movie
and ‘Y’ for color movie

9
04/22/20
Referential Integrity
CREATE TABLE MovieStar CREATE TABLE StarsIn
( name VARCHAR2(30), ( movieTitle VARCHAR2(50),
birthplace VARCHAR2(50), movieYear NUMBER(4),
gender CHAR(1), starName VARCHAR2(30),
birthdate DATE, PRIMARY KEY (movieTitle,
PRIMARY KEY (name) movieYear, starName)
); );

10
04/22/20
Referential Integrity
• Ensures that a value that appears in one relation for a given set of
attributes also appears for a certain set of attributes in another
relation.
– Example: If “Al Pacino” is an actor name appearing in one of
the tuples in the StarsIn relation, then there exists a tuple in
the MovieStar relation for “Al Pacino”.
• Let A be a set of attributes. Let R and S be two relations that
contain attributes A and where A is the primary key of S. A is said
to be a foreign key of R if for any values of A appearing in R
these values also appear in S.

11
04/22/20
Referential Integrity
CREATE TABLE StarsIn
( movieTitle VARCHAR2(50),
movieYear NUMBER(4),
starName VARCHAR2(30),
PRIMARY KEY (movieTitle, movieYear, starName),
FOREIGN KEY (starName) REFERENCES MovieStar(name)
);

12
04/22/20
Maintaining Referential Integrity
• When a referential-integrity constraint is violated, the normal
procedure is to reject the action that caused the violation.
• A foreign key clause can specify that if a delete or update action
on the referenced relation violates the constraint, then, instead of
rejecting the action, the system must take steps to change the
tuple in the referencing relation to restore the constraint.

13
04/22/20
Maintaining Referential Integrity
• The Default Policy: Reject Violating Modifications
– insert a new StarsIn tuple whose starName value is not NULL
and is not the name component of any MovieStar tuple
– update a StarsIn tuple to change the starName component to
a non-NULL value that is not the name component of any
MovieStar tuple.
– delete a MovieStar tuple, and its name component appears as
the starName component of one or more StarsIn tuples.
– update a MovieStar tuple in a way that changes the name
value and the old name is the value of starName in some
StarsIn tuple.

14
04/22/20
Maintaining Referential Integrity
• The Cascade Policy
– Deletes/updates the referencing tuples that refers to the tuple
that was deleted/updated.
– ON [DELETE | UPDATE] CASCADE
– Example:
• when we delete the MovieStar tuple for the actors of a
movie, then to maintain referential integrity the system will
delete the referencing tuple(s) from StarsIn
• If we change the name for some movie stars from c1 to c2,
and there was some StarsIn tuple with c1 as the value of
its starName component, then the system will also update
this starName component to have value c2.

15
04/22/20
Maintaining Referential Integrity
• The Set-Null Policy
– The referencing field is set to null
– ON DELETE SET NULL

• The Set-Default Policy


– The referencing field is set to the default value for the domain
– ON DELETE SET DEFAULT

16
04/22/20
Maintaining Referential Integrity
CREATE TABLE StarsIn
( movieTitle VARCHAR2(50),
movieYear NUMBER(4),
starName VARCHAR2(30),
PRIMARY KEY (movieTitle, movieYear, starName),
FOREIGN KEY (starName) REFERENCES MovieStar(name)
ON DELETE CASCADE
);

17
04/22/20
Maintaining Referential Integrity
• create table course (
course_id char(5) primary key,
title varchar(20),
dept_name varchar(20) references department
)
• create table course (

dept_name varchar(20),
foreign key (dept_name) references department
on delete cascade
on update cascade,
...
)

18
04/22/20
Integrity Constraint Violation During
Transactions
• E.g.,
create table person (
ID char(10),
name char(40),
mother char(10),
father char(10),
primary key ID,
foreign key father references person,
foreign key mother references person)
• How to insert a tuple?
• What if mother or father is declared not null?
– constraint foreign key father references person,
constraint foreign key mother references person)

19
04/22/20
Constraints on Attributes and Tuples
• check (P) where P is a predicate
• Example: ensure that the gender in MovieStar is either ‘F’ for
female and ‘M’ for male
CREATE TABLE MovieStar (
name VARCHAR2(30),
birthplace VARCHAR2(50),
gender CHAR(1) CHECK (gender IN ('F' , 'M')),
birthdate DATE,
PRIMARY KEY (name)
);

20
04/22/20
Attribute-Based CHECK Constraints
• The condition being checked to mention other attributes or tuples
of the relation, or even to mention other relations, but doing so
requires a subquery in the condition.
• The checking of the constraint is associated with the attribute in
question only, not with every relation or attribute mentioned by the
constraint.

• Example:
– starName INT CHECK
(starName IN (SELECT name FROM MovieStar))
What could be wrong??

21
04/22/20
Tuple-Based CHECK Constraints
• The condition of a tuple-based CHECK constraint is checked
every time a tuple is inserted into R and every time a tuple of R is
updated, and is evaluated for the new or updated tuple.
• It is often best to leave complex checks to SQL's "assertions“
• Example:
CREATE TABLE MovieStar (
name VARCHAR2(30) PRIMARY KEY,
birthplace VARCHAR2(50),
gender CHAR(1),
birthdate DATE,
CHECK (gender = ‘F' OR name NOT LIKE 'Ms.%')
);

22
04/22/20
Writing Constraints Correctly
• Many constraints are like above Example , where we want to
forbid tuples that satisfy two or more conditions.
• The expression that should follow the check is the OR of the
negations, or opposites, of each condition.
• This transformation is one of DeMorgan's laws: the negation of the
AND of terms is the OR of the negations of the same terms.
• Thus, in the Example the first condition was that the star is male,
and we used gender = 'F’ as a suitable negation.
• The second condition is that the name begins with 'Ms. ', and for
this negation we used the NOT LIKE comparison. This
comparison negates the condition itself. which would be name
LIKE 'Ms .%‘ in SQL.

23
04/22/20
Tuple-Based CHECK Constraints
• A movie may not be in color if it was made before 1939
• Kevin Bacon was born in 1958, thus he may not appear in a
movie made before 1958

24
04/22/20
Altering Constraints on Tables
• ALTER TABLE is used for both attribute-based and tuple-based
checks.
– DROP CONSTRAINT <constraint name> : drop a constraint
– ADD CONSTRAINT <constraint name> : add a constraint

• Example:
– ALTER TABLE Moviestar ADD CONSTRAINT NameIsKey
PRIMARY KEY (name) ;
– ALTER TABLE MovieStar ADD CONSTRAINT NoAndro
CHECK (gender IN ('F', 'M'));
– ALTER TABLE MovieStar ADD CONSTRAINT RightTitle
CHECK (gender = ‘F’ OR name NOT LIKE 'Ms.%');

25
04/22/20
Assertions
• An assertion is a boolean-valued SQL expression that must be
true at all times.
• Assertion is not associated with any one table.
• The form of an assertion is:
CREATE ASSERTION <name> CHECK (<condition>)
• The condition in an assertion must be true when the assertion is
created and must always remain true; any database modification
whatsoever that causes it to become false will be rejected.
• Any attributes referred to in the condition must be introduced in
the assertion, typically by mentioning their relation in a select-
from-where expression.
• It is normal to aggregate the results of the condition in some way
to make a single true/false choice.

26
04/22/20
Maintaining Referential Integrity
MovieExec(name, address, cert#, networth)

CREATE TABLE Studio (


name CHAR(30) PRIMARY KEY,
address VARCHAR(255),
presC# INT,
FOREIGN KEY (presC#) REFERENCES MovieExec(cert#)
ON DELETE SET NULL
ON UPDATE CASCADE
);

27
04/22/20
Assertions
• Assertion guaranteeing rich studio presidents

CREATE ASSERTION RichPres CHECK


(NOT EXISTS
(SELECT *
FROM Studio, MovieExec
WHERE presC# = cert# AND networth < 10000000
)
);

• We could write it as tuple-based CHECK constraints on the two


relations rather than as a single assertion.

28
04/22/20
Assertions
CREATE TABLE Studio (
name CHAR(30) PRIMARY KEY,
address VARCHAR(255),
presC# INT REFERENCES MovieExec(cert#),
CHECK (presC# NOT IN
(SELECT cert# FROM MovieExec
WHERE networth < 10000000)));

• It will only be checked when a change to its relation, Studio


occurs. It would not catch a situation where the net worth of some
studio president, as recorded in relation MovieExec, dropped
below $10,000.000.

29
04/22/20
Assertions
• The total length of all movies by a given studio shall not exceed
10,000 minutes.

CREATE ASSERTION SumLength


CHECK (10000 >= ALL (SELECT SUM(length)
FROM Movie
GROUP BY studioName));

• We could add to the definition of table Movie the tuple-based


CHECK constraint

CHECK (10000 >= ALL


(SELECT SUM(length) FROM Movie GROUP BY studioName));

30
04/22/20
Assertions
• Unfortunately, none of the commercial DBMS nowadays has
implemented assertion (including Oracle)

31

You might also like