0% found this document useful (0 votes)
13 views10 pages

DBMS Unit 5

Uploaded by

shyam bk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views10 pages

DBMS Unit 5

Uploaded by

shyam bk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Integrity Constraints

Integrity constraints provide a way of ensuring that changes made to the database by authorized users do
not result in a loss of data consistency. Thus, integrity constraints guard against accidental damage to the
database. An integrity constraint can be any arbitrary predicate applied to the database. Integrity
constraints ensure that the data insertion, updating, and other processes have to be performed in such a
way that data integrity is not affected.

Integrity constraints are those constraints in database system which guard against invalid database
operations or accidental damage to the database, by ensuring that authorized changes to the database. It
does not allow to loss of data consistency in database, it ensures database consistency.

Integrity constraints are pre-defined set of rules that are applied on the table fields(columns) or relations
to ensure that the overall validity, integrity, and consistency of the data present in the database table is
maintained

Example of integrity constraints in E-R model:


 Key declaration: candidate key, primary key
 Form of relationship: mapping cardinalities: one to one, one to many etc…

Example of integrity constrains are:


 An account balance cannot be null.
 No two students can have same roll no.

There are four types of integrity constraints in DBMS:


1. Domain Constraint
2. Entity Constraint
3. Referential Integrity Constraint
4. Key Constraint

Evaluation of all the conditions or rules mentioned in the integrity constraint is done every time a table
insert, update, delete, or alter operation is performed. The data can be inserted, updated, deleted, or altered
only if the result of the constraint comes out to be True. Thus, integrity constraints are useful in preventing
any accidental damage to the database by an authorized user.
1) Domain Constraints:
Set of all possible values for attribute known as its domain. Domain constraints are the most elementary
form of integrity constraint. Domain is a pool of values of the same type from which one or more attributes
in one or more tables take their values. Domain constraint is tested by database system whenever a new data
item is entered into database.

Domain Integrity enforces valid entries for a given column by restricting the type, the format, or the range
of possible values. They are tested easily by the system whenever a new data item is entered into the
database.

In the above student table, the attribute A1 draws value from domain D1, A2 from D2 and so on.
Domain integrity means the definition of a valid set of values for an attribute. You define
 data type
 Length or size
 Is null value allowed
 Is the value unique or not for an attribute.

Domain types in SQL: (in 4th chapter)

Consider a Student's table having Roll No(int), Name(char), Age(int) and Class(int) of students.

In the above student's table, the value A in the last row last column violates the domain integrity constraint
because the Class attribute contains only integer values while A is a character.

The CREATE DOMAIN clause can be used to define new domains. For example, to ensure that rating must
be an integer in the range 1 to 10, we could use:
CREATE DOMAIN RATINGVAL INTEGER DEFAULT 0
CHECK (VALUE>= 1 AND VALUE <= 10)
Entity Integrity Constraint:

Entity Integrity Constraint is used to ensure that the primary key cannot be null. A primary key is used to
identify individual records in a table and if the primary key has a null value, then we can't identify those
records. There can be null values anywhere in the table except the primary key column.

Example:
Consider Employees table having Id, Name, and salary of employees

In the above employee's table, we can see that the ID column is the primary key and contains a null value in
the last row which violates the entity integrity constraint.

2) Referential Integrity:

2.1) Basic Concepts:

Consider a pair of relations r(R) and s(S), and the natural join r ⋈ s.
There may be a tuple tr in r that does not join with any tuple in s.
That is, there is no tuple ts in s such that tr[R ∩S] = ts[R ∩S].
We call this a dangling tuple.
Dangling tuples may or may not be acceptable.

A referential integrity constraint is also known as foreign key constraint. A foreign key is a key whose
values are derived from the Primary key of another table. 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 to establish the relationship between tables. For referential integrity to hold in a relational database,
any field in a table that is declared a foreign key can contain either a null value, or only values from a parent
table's primary key. For instance, deleting a record that contains a value referred to by a foreign key in
another table would break referential integrity.

Example
In the Referential integrity constraints, if a foreign key in Table 1 refers to the Primary Key of Table 2, then
every value of the Foreign Key in Table 1 must be null or be available in Table 2.
2.2 Referential integrity in E-R Model
 These constraints arise frequently. Every relation arising from a relationship set has referential integrity
constraints.
 Eg:
Consider relationship set R between entity sets E1 and E2. The relational schema for R includes the
primary keys K1 of E1 and K2 of E2. Then K1 and K2 form foreign keys on the relational schemas for
E1 and E2 respectively that leads referential integrity constraint.

 Eg:
 Figure x below shows an n-ary relationship set R relating entity sets E1, E2,….En
 Let Ki denote the primary key of Ei.
 The attributes of the relation scheme for relationship set R include K1UK2U…….UKn
 Each Ki in the scheme for R is a foreign key that leads to a referential integrity constraint.

Figure: x

 Weak entity sets are also a source of referential integrity constraints. A weak entity set must include the
primary key attributes of the entity set on which it depends

2.3 Database Modification


 Database modifications can cause violations of referential integrity while performing database
modification. Referential-integrity constraints rules should not be violated.
 The following tests must be made in order to preserve the following referential integrity constraint:
Πα (r2) ⊆ ΠK (r1)
r1 r2
roll_no name address course_id course_name roll_no
1 shyam punarwas C1 DBMS 1
2 kumar dhangadhi C2 C Network 2
3 sital attriya C3 Programming 3
4 ram mahendranagar C4 Business 4

Insert: If a tuple t2 is inserted into r2, the system must ensure that there is a tuple t1 in r1 such that t1[K] =
t2[α].
That is, t2 [α] ∈ ΠK (r1)

Delete: If a tuple, t1 is deleted from r1, the system must compute the set of tuples in r2 that reference t1:

σα = t1[K] (r2)

Note: If this set is not empty, either reject delete command, or delete also the tuples that
reference t1. [cascading deletions are possible(on delete cascade, on delete set null, on
delete no action)].

Update: There are two cases:

1) If a tuple t2 is updated in relation r2 and the update modifies values for foreign key α, then
a test similar to the insert case is made:
 Let t2’ denote the new value of tuple t2. The system must ensure that
t2’[α] ∈ ΠK(r1)

2) If a tuple t1 is updated in r1, and the update modifies values for the primary key
(K), then a test similar to the delete case is made:

1) The system must compute


σα = t1[K] (r2)
using the old value of t1 (the value before the update is applied).

2) If this set is not empty


i) the update may be rejected as an error, or
ii) the update may be cascaded to the tuples in the set, or
iii)the tuples in the set may be deleted.

2.4 Referential Integrity in SQL:

In addition to the original standard allows specification of primary and candidate keys and foreign keys as
part of the create table command:
 primary key clause includes a list of attributes forming the primary key.
 unique key clause includes a list of attributes forming a candidate key.
 foreign key clause includes a list of attributes forming the foreign key, and the name of the relation
referenced by the foreign key.

An example illustrates several features mentioned so far:


create table customer
(cname char(20) not null,
street char(30),
city char(30),
primary key (cname))

create table branch


(bname char(15) not null,
bcity char(30),
assets integer,
primary key (bname)
check (assets >= 0))

create table account


(account# char(10) not null,
(bname char(15),
balance integer,
primary key (account#)
foreign key (bname) references branch,
check (balance >= 0))

create table depositor


(cname char(20) not null,
account# char(10) not null,
primary key (cname, account#)
foreign key (cname) references customer,
foreign key (account#) references account)

Notes on foreign keys:


 A short form to declare a single column is a foreign key.
bname char(15) references branch

 When a referential integrity constraint is violated, the normal procedure is to reject the action. But a
foreign key clause in SQL-92 can specify steps to be taken to change the tuples in the referenced
relation to restore the constraint.

Cascading actions
Syntax
create table account
...........
foreign key (bname) references branch
on delete cascade
on insert cascade,
............

on delete cascade: if a delete of a tuple in branch results referential-integrity constraint violation, it also
delete tuples in relation account that refers to the branch that was deleted.
on update cascade : if a update of a tuple in branch results referential-integrity constraint violation, it
updates tuples in relation account that refers to the branch that was updated.
Assertion
 Assertion are used to specify integrity constraints which can not be specified using constraint like
Primary Key, Not Null, Unique, Check etc…
 Assertions = conditions that the database must always satisfy
 Domain constraints and referential-integrity constraints are specific forms of assertions
 CHECK – verify the assertion on one-table, one-attribute
 ASSERTION – verify one or more tables, one or more attributes

 Where a constraint (Domain constraints and referential-integrity constraints) cannot be expressed in these
forms, we use an assertion,
 DBMS tests for assertion for it’s validity when it is created.

 An assertion in DQL-92 takes the form,

create assertion <assertion-name>


check <predicate>;

drop assertion <assertion-name>

Example
The price of Textbook must not be less than the minimum price of a Novel.

CREATE ASSERTIO price_constraint


CHECK (Not Exists(SELECT * FROM Book [Not Exits :the result of this query must be empty]
WHERE category = ‘Textbook’
AND (price<(SELECT MIN(price)
FROM Book
WHERE category = ‘Novel’))));

Note: Assertion is violated whenever the result of query inside Not Exists clause is not empty.

Example
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 Movies
GROUP BY studioName ) )
Example

Triggers

Triggers are the SQL statements that are automatically executed when there is any change in the database.
The triggers are executed in response to certain events(INSERT, UPDATE or DELETE) in a particular
table. These triggers help in maintaining the integrity of the data by changing the data of the database in a
systematic fashion.

A trigger is a stored procedure in database which automatically invokes whenever a special event in the
database occurs. For example, a trigger can be invoked when a row is inserted into a specified table or when
certain table columns are being updated.

Syntax
create trigger Trigger_name
(before | after)
[insert | update | delete]
on [table_name]
[for each row]
[trigger_body]

1. CREATE TRIGGER: These two keywords specify that a triggered block is going to be declared.
2. TRIGGER_NAME: It creates or replaces an existing trigger with the Trigger_name. The trigger
name should be unique.
3. BEFORE | AFTER: It specifies when the trigger will be initiated i.e. before the ongoing event or
after the ongoing event.
4. INSERT | UPDATE | DELETE: These are the DML operations and we can use either of them in
a given trigger.
5. ON[TABLE_NAME]: It specifies the name of the table on which the trigger is going to be
applied.
6. FOR EACH ROW: Row-level trigger gets executed when any row value of any column changes.
7. TRIGGER BODY: It consists of queries that need to be executed when the trigger is called.
Eg,
Suppose we have a table named Student containing the attributes Student_id, Name, Address, and Marks.

Now, we want to create a trigger that will add 100 marks to each new row of the Marks column
whenever a new student is inserted to the table.

The SQL Trigger will be:

CREATE TRIGGER Add_marks

BEFORE

INSERT

ON Student

FOR EACH ROW

SET new.Marks = new.Marks + 100;

Note: The new keyword refers to the row that is getting affected.

After creating the trigger, we will write the query for inserting a new student in the database.

INSERT INTO Student(Name, Address, Marks) VALUES('Alizeh', 'Maldives', 110);

The Student_id column is an auto-increment field and will be generated automatically when a new
record is inserted into the table.

To see the final output the query would be:

SELECT * FROM Student;


Advantages of Triggers
1. Triggers provide a way to check the integrity of the data. When there is a change in the database
the triggers can adjust the entire database.
2. Triggers help in keeping User Interface lightweight. Instead of putting the same function call all
over the application you can put a trigger and it will be executed.

Disadvantages of Triggers
1. Triggers may be difficult to troubleshoot as they execute automatically in the database. If there is
some error then it is hard to find the logic of trigger because they are fired before or after
updates/inserts happen.
2. The triggers may increase the overhead of the database as they are executed every time any field is
updated.

You might also like