Database Constraints
Database Constraints
Data Integrity
Ensures the consistency and correctness of
data stored in a database.
Entity Integrity - ensures that each row can be uniquely identified by an attribute called the primary
key. The primary key cannot be NULL.
Example:
Student ID. It ensures that student ID must be unique (no duplication) and must be of the same data type.
Domain Integrity - ensures that only a valid range of values is allowed to be stored in a column.
Example:
City Name. It must ensure that only valid city name can be entered in the city column of an Address Table.
Referential Integrity - ensures that the values of the foreign key match with the value of the
corresponding primary key.
Example:
College Course Code. It ensures that Course Code (foreign key) being entered matches with value of the
corresponding primary key in another table.
PRIMARY KEY constraints identify one or more columns in a table that constitute a primary key
One PRIMARY KEY constraint is allowed per table
Value must be unique across constituent columns
Null values are not allowed in constituent columns
Syntax / Example:
Create Table Customer
(
CustID int not null constraint pk_CustID primary key clustered,
Name varchar(50)
)
or
Alter Table Customer
add constraint pk_CustID primary key clustered (CustID)
Note: CustID should be defined as not null
UNIQUE Constraints
Syntax / Example:
Create Table Customer
(
CustID int not null,
Name varchar(50),
Citizenship char(15) ,
SSSNochar(15) constraint unq_SSSNo unique
)
or
Alter Table Customer
Add constraint unq_SSSNo unique (SSSNo)
FOREIGN KEY constraints ensure referential integrity between columns in same or different tables
Must reference a PRIMARY KEY or UNIQUE constraint
User must have REFERENCES permission on referenced table
Syntax / Example:
Create Table CustSales
(
CustSalesID int not null,
CustIDchar(10) constraint fk_CustIDforeign key references Customer (CustID),
Receipt_Amount decimal(10,2)
)
or
Alter Table Customer
Add constraint fk_CustID foreign key (CustID) references Customer (CustID)
CHECK Constraints
CHECK constraints restrict the values that can be entered into a column on INSERT or UPDATE
Can define multiple CHECK constraints per column
Can reference columns in the same table
Cannot contain subqueries
Syntax / Example:
Create Table Customer
(
CustID int not null, Name varchar(50),
Citizenship char(15) constraint chk_citizenship check
(Citizenship in ('Filipino', Japanese', 'Chinese', 'Australian', 'American'))
)
or
Alter Table Customer
Add constraint chk_Citizenship check (Citizenship in ('Filipino', Japanese','Chinese','Australian','American'))
DEFAULT Constraints
Syntax / Example:
Create Table Customer
(
CustID int not null,
Name varchar(50),
Citizenship char(15) constraint df_Citizenship default 'Filipino
)
or
Alter Table Customer
Add constraint df_Citizenship default Filipino for Citizenship
End of Lecture