MySQL IC

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

Database Systems

Integrity Constraints - MySQL

Nguyễn Văn Diêu

HO CHI MINH CITY UNIVERSITY OF TRANSPORT

2023

Kiến thức - Kỹ năng - Sáng tạo - Hội nhập


Sứ mệnh - Tầm nhìn
Triết lý Giáo dục - Giá trị cốt lõi
Outline I

1 Integrity Constraints

2 Create Constraints

3 MySQL Common Constraints


Not Null
Unique
Primary Key
Check
Default

4 Foreign Key Constraint

5 Integrity Constraints - General Algorithm

Nguyễn Văn Diêu Table of Contents 2/31


Integrity Constraints

Parts of Integrity Constraints


Suppose R(ABC) with B > C
There is an integrity constraint of scheme R.
Integrity Constraints
• Context: R
• Condition:
∀t ∈ ∀r
t.B > t.C
end;
• Influence table:
Insert Delete Update
R + - +(B/C)

Nguyễn Văn Diêu 1. Integrity Constraints 3/31


Parts of Integrity Constraints

• In influence table, plus(+) sign if statement (operation) on relation maybe enforce


business rule’s wrong. Otherwise, minus(-) sign.
• With plus sign we write one Trigger to control that operation.
• Trigger is an event-driven action that is run automatically when a specified
change operation ( INSERT, UPDATE, and DELETE statement) is performed on
a specified table.
• Triggers are useful for tasks such as enforcing business rules, validating input data,
and keeping an audit trail.

Nguyễn Văn Diêu 1. Integrity Constraints 4/31


Create Constraints

• Created with the CREATE TABLE statement.


Create Table table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);

• Ater the table is created with the Alter Table statement.

Nguyễn Văn Diêu 2. Create Constraints 5/31


MySQL Constraints

• Not Null: Ensures that a column cannot have a Null value.


• Unique: Ensures that all values in a column are different.
• Primary Key: A combination of a Not Null and Unique. Uniquely identifies
each row in a table.
• Foreign Key: Prevents actions that would destroy links between tables.
• Check: Ensures that the values in a column satisfies a specific condition.
• Default: Sets a default value for a column if no value is specified.
• Create Index: Used to create and retrieve data from the database very quickly.

Nguyễn Văn Diêu 3. MySQL Common Constraints 6/31


Not Null

The Not Null constraint enforces a column to Not accept Null values.
e.g.
Create Table Product (
ProductID char(3) Primary Key,
ProductName varchar(30) Not Null,
Price float,
CategoryID char(3) Not Null,
);

Nguyễn Văn Diêu 3. MySQL Common Constraints :: Not Null 7/31


Not Null

Using Alter Table for table is created


e.g.
Alter Table Product
Modify ProductName varchar(30) Not Null ,
Modify CategoryID char(3) Not Null ;

Nguyễn Văn Diêu 3. MySQL Common Constraints :: Not Null 8/31


Unique

• The Unique constraint ensures that all values in a column are different.
• Both the Unique and Primary Key constraints provide a guarantee for uniqueness
for a column or set of columns.
• A Primary Key constraint automatically has a Unique constraint.
e.g.
Create Table Product (
ProductID char(3) Primary Key,
ProductName varchar(30),
Price float,
CategoryID char(3),
Unique(ProductName)
);

Nguyễn Văn Diêu 3. MySQL Common Constraints :: Unique 9/31


Unique

Using Alter Table for table is created


e.g.
Alter Table Product
Add Constraint Pro_Uni Unique (ProductName) ;

Nguyễn Văn Diêu 3. MySQL Common Constraints :: Unique 10/31


Primary Key

• The Primary Key constraint uniquely identifies each record in a table.


• Primary keys must contain Unique values, and cannot contain Null values.
• A table can have only ONE primary key; and in the table, this primary key can
consist of single or multiple columns (fields).

Using Alter Table for table is created


e.g.
Alter Table Product
Add Primary Key (ProductID) ;

If primary Key is multiple columns:


e.g.
Alter Table OrderDetail
Add Constraint PK_OrD Primary Key (OrderID, ProductID) ;
Nguyễn Văn Diêu 3. MySQL Common Constraints :: Primary Key 11/31
Check

• The Check constraint is used to limit the value range that can be placed in one or
multiple columns.
e.g.
Create Table Product (
ProductID char(3) Primary Key,
ProductName varchar(30),
Price float,
Quality int,
CategoryID char(3),
Check (Price > 0)
);

Nguyễn Văn Diêu 3. MySQL Common Constraints :: Check 12/31


Check

• Check multiple columns

e.g.
Create Table Product (
ProductID char(3) Primary Key,
ProductName varchar(30),
Price float,
Quality int,
CategoryID char(3),
Constraint CKH_Price Check (Price > 0 And Quality >=5)
);

Nguyễn Văn Diêu 3. MySQL Common Constraints :: Check 13/31


Check

Using Alter Table for table is created


e.g.
Alter Table Product
Add Check (Price > 0) ;

For Check multiple column

Alter Table Product


Add Constraint CHK_Price_Quality (Price > 0 And Quality >=5) ;

Drop Check:

Alter Table Product


Drop Check CHK_Price_Quality ;

Nguyễn Văn Diêu 3. MySQL Common Constraints :: Check 14/31


Default

• The Default constraint is used to set a default value for a column.


• The default value will be added to all new records, if no other value is specified. e.g.

Create Table Product (


ProductID char(3) Primary Key,
ProductName varchar(30),
Price float,
Quality int Default 5,
CategoryID char(3)
);

Nguyễn Văn Diêu 3. MySQL Common Constraints :: Default 15/31


Default

Using Alter Table for table is created


e.g.
Alter Table Product
Alter Quality Set Default 5 ;

Nguyễn Văn Diêu 3. MySQL Common Constraints :: Default 16/31


Foreign Key Constraints

Foreign key: In a relation, attributes (one or many) are called foreign key if they are
not a key in this relation, but a primary key in another relation.
Foreign key assert that a value appearing in one relation must also appear in the
primary key component(s) of another relation.
e.g.
Class(ClassID, Description)
C01
C02
Student(StudentID, Name, Address, Email, ClassID)
C01
C02
C02

C03


Nguyễn Văn Diêu 4. Foreign Key Constraint 17/31


Foreign Key Constraints

Let R1 (XY), R2 (Z, X)


Declaring attributes of relation to be a foreign key, referencing some attribute(s) of a
second relation (possibly the same relation) must be have twofold:
• Attribute(s) X of the R1 relation must be declared UNIQUE or the PRIMARY
KEY. Otherwise, R2 cannot make the foreign key declaration.
• π X (R2 ) ⊆ π X (R1 )

Nguyễn Văn Diêu 4. Foreign Key Constraint 18/31


Foreign Key Constraints

When foreign key constraint is declared, the system has to reject the violating
modification.
There are two policy for Update and Delete tuples in foreign key:
1. Default policy: Reject Violating Modifications.
2. Cascade policy: When changes to the referenced attribute(s) in R1 . There are
following change to the foreign key in R2 .
3. Null policy: When a modification to the referenced relation (R1 ) affects a
foreign-key value (in R2 ) is changed to NULL.

Usually declare: Update Cascade; Delete Set Null.

Nguyễn Văn Diêu 4. Foreign Key Constraint 19/31


Foreign Key Constraints

CREATE TABLE R2 (
Z datatype,
X datatype,
Foreign Key (X) References R1 (X)
[On Update reference_option ]
[On Delete reference_option ] ) ;

reference_option: Restrict | Cascade | Set Null | No Action | Set Default

Nguyễn Văn Diêu 4. Foreign Key Constraint 20/31


Foreign Key Constraints

e.g.
Create Table OrderDetail (
OrderID char(3),
ProductID char(3),
Quantity int,
Primary Key (OrderID, ProductID),
Constraint FK_Order Foreign Key (OrderID) References Order(OrderID)
On Delete Set Null On Update Cascade,
Constraint FK_Prod Foreign Key (ProductID) References Products(ProductID)
On Delete Set Null On Update Cascade
);
Drop Foreign key:
Alter Table OrderDetail Drop Foreign Key FK1;
Nguyễn Văn Diêu 4. Foreign Key Constraint 21/31
General Algorithm

CREATE TRIGGER trigger_name


trigger_time trigger_event
ON tbl_name
FOR EACH ROW
[trigger_order]
trigger_body ;

trigger_time:{ BEFORE | AFTER }


trigger_event: { INSERT | UPDATE | DELETE }
trigger_order: { FOLLOWS | PRECEDES } other_trigger_name
INSERT trigger, NEW.column_name indicates a column value
DELETE trigger, OLD.column_name indicates a column value
UPDATE trigger, OLD.column_name and NEW.column_name indicates a column
value
Nguyễn Văn Diêu 5. Integrity Constraints - General Algorithm 22/31
General Algorithm

e.g.
DELIMITER $$
CREATE TRIGGER Price_check
BEFORE UPDATE
ON Product
FOR EACH ROW
BEGIN
IF NEW.Price < 0 THEN
SET NEW.Price = 0;
ELSEIF NEW.Price > 100 THEN
SET NEW.Price = 100;
END IF;
END;
$$
Nguyễn Văn Diêu 5. Integrity Constraints - General Algorithm 23/31
General Algorithm

General Algorithm for Trigger of Integrity Constraints


DELIMITER $$
CREATE TRIGGER trigger_name
trigger_time trigger_event
ON tbl_name
FOR EACH ROW
BEGIN
IF Exists (False of creteria) THEN
SIGNAL SQLSTATE ’45000’
SET MESSAGE_TEXT =’Message’ ;
END IF ;
END;
$$

Nguyễn Văn Diêu 5. Integrity Constraints - General Algorithm 24/31


General Algorithm

e.g.
DELIMITER $$
CREATE TRIGGER GreaterThanZero
BEFORE INSERT
ON Product
FOR EACH ROW
BEGIN
IF NEW.Price <=0 THEN
SIGNAL SQLSTATE ’45000’
SET MESSAGE_TEXT =’Price must greater than zero’ ;
END IF ;
END ;
$$

Nguyễn Văn Diêu 5. Integrity Constraints - General Algorithm 25/31


General Algorithm

e.g.
Create table R(A,B); A, B: integer;
Constraint: A >= B; Do not allow delete if A > 2*B.

Integrity Constraints
• Context: R
• Condition:
∀t ∈ ∀r
t.A ≥ t.B and not allow delete if A > 2 ∗ B
end;
• Influence table:
Insert Delete Update
R + + +(A/B)

Nguyễn Văn Diêu 5. Integrity Constraints - General Algorithm 26/31


e.g. Insert Trigger

delimiter $$
create trigger insert_R before insert on R
for each row
begin
if new.A < new.B then
signal sqlstate ’45000’
set message_text = ’Insert error: A < B’;
end if;
end;
$$

Nguyễn Văn Diêu 5. Integrity Constraints - General Algorithm 27/31


e.g. Delete Trigger

delimiter $$
create trigger delete_R before delete on R
for each row
begin
if old.A > 2 * old.B then
signal sqlstate ’45000’
set message_text = ’Delete error: A > 2*B’;
end if;
end;
$$

Nguyễn Văn Diêu 5. Integrity Constraints - General Algorithm 28/31


e.g. Update Trigger

delimiter $$
create trigger update_R before update on R
for each row
begin
if new.A < new.B then
signal sqlstate ’45000’
set message_text = ’Update error: A < B’;
end if;
end;
$$

Exercises:
R1(A, B); R2(B, C); A, B, C : integer.
Constraint: A > C.

Nguyễn Văn Diêu 5. Integrity Constraints - General Algorithm 29/31


e.g. Multiple Relations Constraint

R1(A, B); R2(B, C); A, B, C : integer. Constraint: A > C.


Integrity Constraints
• Context: R1 , R2
• Condition:
∀t ∈ ∀(r = r1 ▷◁ r2 )
t.A > t.C
end;
• Influence table:
Insert Delete Update
R1 + - +(A/B)
R2 + - +(B/C)

Nguyễn Văn Diêu 5. Integrity Constraints - General Algorithm 30/31


e.g. Multiple Relations Constraint

Insert Trigger for R1:

delimiter $$
create trigger insert_R1 before insert on R1
for each row
begin
if Exists (Select *
From R2
Where new.B = B and new.A <= C ) then
signal sqlstate ’45000’
set message_text = ’Insert R1 Error: A <= C’;
end if;
end;
$$

Nguyễn Văn Diêu 5. Integrity Constraints - General Algorithm 31/31

You might also like