It is often told, data without integrity is just numbers.
There are different situations like
1. When a user enters data which is not in proper range or invalid
2. A wrong DML operation is attempted by the user or by any bug in the code
3. Data from the related table are tried to be modified, and many other situations where data accuracy need to be verified.
Here is the use of data integrity.
It defines the consistency, accuracy, completeness and reliability of data.
To implement this data integrity, we use various constraints in the database.
In SQL Server, there are mainly two kinds of data integrity:
1. System-defined or Predefined integrity
2. User-Defined integrity
System defined / Predefined integrity:
Entity Integrity
- This integrity is used to ensure uniqueness and availability of data.
- Primary Key, Unique, Not null
Code: create table Student
(
student_id varchar(10) primary key,
name varchar(30)not null,
email varchar(50) unique,
contact_number varchar(12) unique not null,
)
Referential Integrity
- this integrity is used when we refer to other tables
- foreign key
- When we use the primary key of one table in another table, it is called a foreign key
Code:create table usertable (userid varchar(10) primary key,name varchar(20));
create table logintable(userid varchar(10) foreign key references usertable(userid),password varchar(20));
Domain Integrity
- Entity and referential integrity apply to the columns
- domain integrity will apply to the values of the data
- it is implemented using Check and Default constraints
Code:create table Student
(
student_id varchar(10) primary key,
name varchar(30)not null,
email varchar(50) unique,
contact_number varchar(12) unique not null,
university varchar(30) not null default 'MyUniversity'
)
create table Student
(
student_id varchar(10) primary key,
name varchar(30)not null,
email varchar(50) unique,
age int check(age between 18 and 22),
contact_number varchar(12) unique not null,
university varchar(30) not null default 'MyUniversity'
)
User-defined Integrity
-User-defined integrity allows the user to apply business rules to the database that aren’t covered by any of the other three data integrity types.
- we implement this using stored procedures, triggers and constraints on column and table label.