Integrity Constraints

27
Integrity Constraints

description

Integrity Constraints. Integrity Constraints. Integrity constraints ensure that changes (update deletion, insertion) 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. - PowerPoint PPT Presentation

Transcript of Integrity Constraints

Page 1: Integrity Constraints

Integrity Constraints

Page 2: Integrity Constraints

Integrity Constraints

Integrity constraints ensure that changes (update deletion, insertion) 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.

Database integrity refers to the validity and consistency of stored data. Integrity is usually expressed in terms of constraints, which are consistency rules that the database is not permitted to violate. Constraints may apply to each attribute or they may apply to relationships between tables. For examples: an integrity constraint could state that

A student’s grade point average cannot be less than 0.00 or grater than 4.00.

A brood group must be ‘A’ or ‘B’ or ‘AB’ or ‘O’ only (can not any other values else).

A branch name contained in the table account and loan, representing the branch that the customer opens an account or a loan, must correspond to an existing branch name in the table branch.

Page 3: Integrity Constraints

Integrity Constraints

Integrity Constraints can be categorized into 4 types :

Domain Constraints

Referential Integrity

Triggers

Functional Dependency

Page 4: Integrity Constraints

Domain Constraints

Since every attribute has an associated domain, there are constraints (called domain constraints) in the form of restrictions on the set of values allowed for the attributes of relations. (A requirement that the values of an attribute must come from a specific domain).

Domain Constraints are the most elementary form of integrity constraint. They are tested easily by the system whenever a new data item is entered into the database.

Page 5: Integrity Constraints
Page 6: Integrity Constraints

Referential Integrity

Referential Integrity is a constraint to enforce relationship between primary key of one relation and foreign key of the other. Referential Integrity is used to ensure that each value of a foreign key attribute refers to an entity that appears in the foreign table. As with other constraints, any attempt to modify the database contents that would cause a foreign key constraint violation must be disallowed. Relational database systems provide enforcement of referential integrity constraints. The constraint is specified in the database schema, and the database system enforces it.

Referential Integrity: Basic Concept

Page 7: Integrity Constraints

Referential Integrity: Basic Concept

Consider a pair of relations r and s and the natural join between r and s. There may be a tuple tr in r that does not join with any tuple in s. That is, there is no ts in s such that tr[R S] = ts[R S]. Such tuples are called dangling tuples. Depending on the entity set or relationship set being modeled, dangling tuples may or may not be acceptable.

Suppose there is a tuple t1 in the account relation with t1[branch_name] = “Ngamvongvan”, but there is no tuple in the branch relation for the “Ngamvongvan” . This situation would be undesirable. We expect the branch relation to list all bank branches. Therefore, tuple t1 would refer to an account at a branch that does not exist. Clearly, we would like to have an integrity constraints that prohibits the occurrence of dangling tuples in database.

Page 8: Integrity Constraints

Referential Integrity constraint can be written as

(r2) k (r1)

The important of this rule is when referencing from one relation to the other, DBMS must ensure that the instances in both relations must exist.

(ความสำ�าค�ญของกฎข�อนี้��ค�อ เม��อม�การอ�างอ�งจากร�เลชั่��นี้หนี้��งไปยั�งอ�กร�เลชั่��นี้หนี้��งแล�ว ระบบการจ�ดการฐานี้ข�อม%ลต้�องร�บประก�นี้ว'าข�อม%ลในี้ร�เลชั่��นี้ทั้��ง 2 จะต้�องม�ต้�วต้นี้เสำมอ)

foreign key of r2 must be a subset of Primary key of r1

Note that, for a referential integrity constraint to make sense, either must be equal to K, or and K must be compatible sets of attributes.

Page 9: Integrity Constraints
Page 10: Integrity Constraints
Page 11: Integrity Constraints

Trigger

Trigger is rule managed by a DBMS. Because a trigger involves an event, a condition, and a sequence of actions, it also is known as an event-condition-action rule. Writing the action part or trigger body is similar to writing a procedure or a function except that a trigger has no parameters. Triggers are executed by the rule system of the DBMS not by explicit calls as for procedures and functions.

Trigger is a type of stored procedure which would be alarmed (fired) every time instance of database is modified (inserted, updated, or deleted). Trigger is used to prevent a modification of unreasonable values to a database.

A trigger is a statement that the system executes automatically as a side effect of a modification to the database.

SQL-based database systems use triggers widely. Unfortunately, each DBMS implemented its own syntax for triggers, leading to incompatibilities.

Page 12: Integrity Constraints

Motivation and Classification of Triggers

Triggers are widely implemented in DBMSs because they have a variety of uses in business applications. The typical uses of triggers :-

• Complex integrity constraints: Integrity constraints that cannot be declaratively specified by check constraints in CREATE TABLE statements.

• Transition constraints: Integrity constraints that compare the values before and after an update occurs.

• Update propagation: Update derived columns in related tables.

• Exception reporting: Create a record of unusual conditions as an alternative to rejecting a transaction.

Page 13: Integrity Constraints

Triggers, which are part of SQL:1999, classifies triggers by granularity, timing, and applicable event.

For granularity, a trigger can involve each row affected by an SQL statement or an entire SQL statement. Row triggers are more common than statement triggers.

For timing, a trigger can fire before or after an event. Typically, triggers for constraint checking fire before an event, while triggers updating related tables and performing other actions fire after an event.

For applicable event, a trigger can apply to INSERT, UPDATE, and DELETE statements.

Page 14: Integrity Constraints

A trigger can be created to maintain database consistency in term of Data Integrity , Referential Integrity and Encapsulate Business Rules. To design a trigger mechanism, we must meet 2 requirements:

1. Specify when a trigger is to be executed. This is broken up into an event that causes the trigger to be checked and a condition that must be satisfied for trigger execution to proceed.

2. Specify the actions to be taken when the trigger executes.

Once we enter a trigger into the database, the database system takes on the responsibility of executing it whenever the specified event occurs and the corresponding condition is satisfied.

Page 15: Integrity Constraints

Understanding of transition table.

Inserted and deleted are transition table. While a trigger is being executed, special and temporary tables, Inserted and Deleted, are automatically created in main memory. These 2 tables are existed within an execution time of a trigger. When a trigger complete its execution, the tables are destroyed. When first being created, schema (name, number and data type of attribute) of a transition table is similar to a table in which a trigger reside.

An event involved with database modification causes an insertion of a record into this special table as following:

INSERT : When a new record is inserted into a table in which a trigger reside, DBMS will insert this record into INSERTED table simultaneously. DELETE: When an existing record is deleted from a table in which a trigger reside, DBMS will insert this record into DELETED table simultaneously. UPDATE: When an update occurs in a table in which a trigger reside, DBMS will perform 2 following steps: storing the before-updated record into DELETED table and storing modified record into INSERTED table.

These transition tables used to store data items due to insertion, deletion or update enable trigger to detect consistency as required.

Page 16: Integrity Constraints

BookID BookName avail

B01 Finance Y

B02 Accounting Y

B03 Database Y

B04 Data Communication Y

B05 Automata Y

B06 Stock and Bond Y

B07 Image Processing Y

B08 Embedded System Y

B09 Architecture Y

B10 Data Structure y

CREATE TRIGGER borrow_deleteon borrowfor deleteas update book set avail = 'Y' where bookID in (select bookID from deleted);

CREATE TRIGGER borrow_inserton borrowfor insertas update book set avail = 'N' where BookID in (Select BookID from inserted);

Create Trigger Book_UpdateOn bookFor updateAs If update (BookID) Begin declare @newID char(5) select @newID = i.bookID from inserted as i Update borrow Set BookID = @newID where bookID in (Select BookID from deleted))

Page 17: Integrity Constraints

Example of Need for Triggers

Triggers are useful mechanisms for alerting humans or for starting certain tasks automatically when certain conditions are met. As an illustration, suppose that, instead of allowing negative account balances, the bank deals with overdrafts by setting the account balance to zero, and creating a loan in the amount of the overdraft. The bank gives this loan a loan number identical to the account number of the overdrawn account. For this example, the condition for executing the trigger is an update to the account relation that results in a negative balance value. Suppose that Jones’ withdrawal of some money from an account made the account balance negative. Let t denote the account tuple with a negative balance value. The actions to be taken are:

• Insert a new tuple s in the loan relation withs [loan_number] = t [account_number]s [branch_name] = t [branch_name]s [amount] = t [balance]

(Note that, since t [balance] is negative, we negate t [balance] to get the loan amount – a positive number.

• Insert a new tuple u in the borrower relation with u [customer_name] = “Jones” u [loan_number] = t [account_number]

•Set t [balance] to 0.

Page 18: Integrity Constraints
Page 19: Integrity Constraints

//create trigger overdraft_trigger after update of balance on accountCreate trigger overdraft_trigger after update on accountReferencing new row as nrowFor each row When nrow.balance < 0 Begin atomic

insert into borrower(select customer_name, account_number from depositor where nrow.account_number = depositor.account_number)

insert into loan values(nrow.account_number, nrow.branch_name, -nrow.balance)

update account set balance = 0where account.account_number = nrow.account_numberend

Example of a trigger that automate an application according to general business logic.

Page 20: Integrity Constraints

This trigger definition specifies that the trigger is initiated after any update of the relation account is executed. An SQL update statement could update multiple tuples of the relation, and the for each row clause in the trigger code would then explicitly iterate over each updated row.

The referencing new row as clause creates a variable nrow (called a transition table variable), which stores the value of an updated row after the update.

The when statement specifies a condition, namely nrow.balance < 0. The system executes the rest of the trigger body only for tuples that sattisfy the condition. The begin atomic… end clause serves to collect multiple SQL statements into a single compound statement. The two insert statements with the begin..end structure carry out the specific tasks of creating new tuples in the borrower and loan relations to represent the new loan. The update statement serves to set the account balance back to 0 from its earlier negative value.

Page 21: Integrity Constraints

As another example of the use of triggers, suppose a warehouse wishes to maintain a minimum inventory of each item; when the inventory level of an item falls below the minimum level, an order should be placed automatically. This is how the business rule can implemented by triggers:

On an update of the inventory level of an item, the trigger should compare the level with the minimum inventory level for the item, and if the level is at or below the minimum, a new order is added to an orders relation.

Page 22: Integrity Constraints

CREATE TRIGGER tr_InsUpdtmpSales On tmp_sales for insert, update as declare @quantity int select @quantity = i.qty from inserted as i if @quantity < 20 begin print 'No record to insert or update' print 'Because quantity must more than 20' rollback transaction end

Page 23: Integrity Constraints

CREATE TRIGGER tr_InsUpdtmpSales2On tmp_salesfor update asif update(qty) declare @quantity int select @quantity = i.qty from inserted as i if @quantity < 20 begin print 'No record to insert or update' print 'Because quantity must more than 20' ROLLBACK TRANSACTION endelse print 'Triggers not done because qty column is not updated'

Page 24: Integrity Constraints

Performing of delete cascading by Trigger

We can utilize a trigger to perform delete cascading. That is a deletion of a tuple in a major table makes the tuple of another table whose foreign key is a subset of the primary of that major table to be deleted accordingly.

Create TRIGGER tr_DelBorrowDeleteOn borrowfor delete asdeclare @rowcount intraiserror('%d rows are going to be deleted from table borrow',0,1,@rowcount)

CREATE TRIGGER trbookdelon bookfor delete asdelete borrow from deleted as d where borrow.bookID = d.bookID

Page 25: Integrity Constraints

Types of Trigger

FOR Trigger or AFTER Trigger is a trigger which fires after transac-SQL instruction already modified (insert, update, or delete) database instance. The execution steps of after trigger :

1. Transac-SQL (insert, update or delete) performs on a specific relation.2. DBMS checks the relation’s constraints specified in the trigger.3. DBMS creates INSERTED or DELETED as required.4. Start the execution of FOR or AFTER Trigger.

Example:

Create trigger overdraft-trigger after update of balance on account relation: The update statement will adjust an account balance from negative value to 0.

Page 26: Integrity Constraints

BEFORE Triggers : Such triggers can serve as extra constraints that can prevent invalid updates. For instance, if we wish not to permit overdrafts, we can create a before trigger that rolls back the transaction if the new balance is negative. As another example, suppose the value in a phone number field of an inserted tuple is blank, which indicates absence of a phone number. We can define a trigger that replaces the value by the 02-942-8555. The set statement can be used to carry out such modifications. create trigger setnew_trigger before update on customer referencing new row as nrow for each row when nrow.phone_number = ' ' set nrow.phone_number = '02-942-8555'

Page 27: Integrity Constraints

CASE STUDY