SQL Constraints: Constraint
SQL Constraints: Constraint
SQL Constraints are rules used to limit the type of data that can go into a table, to maintain the
accuracy and integrity of the data inside table.
Constraints can be divided into the following two types,
Constraints are used to make sure that the integrity of data is maintained in the database. Following
are the most used constraints that can be applied to a table.
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
UNIQUE Constraint
UNIQUE constraint ensures that a field or column will only have unique values.
A UNIQUE constraint field will not have duplicate data. This constraint can be applied at column
level or table level.
Using UNIQUE constraint when creating a Table (Table
Level)
Here we have a simple CREATE query to create a table, which will have a column s_id with unique
values.
CREATE TABLE Student(s_id int NOT NULL UNIQUE, Name varchar(60), Age int);
The above query will declare that the s_id field of Student table will only have unique values and
wont take NULL value.
Order_Detail Table
10 Order1 101
11 Order2 103
12 Order3 102
In Customer_Detail table, c_id is the primary key which is set as foreign key
in Order_Detail table. The value that is entered in c_id which is set as foreign key
in Order_Detail table must be present in Customer_Detail table where it is set as primary key.
This prevents invalid data to be inserted into c_id column of Order_Detail table.
If you try to insert any incorrect data, DBMS will return error and will not allow you to insert the
data.
Using FOREIGN KEY constraint at Table Level
CREATE table Order_Detail(
order_id int PRIMARY KEY,
order_name varchar(60) NOT NULL,
c_id int FOREIGN KEY REFERENCES Customer_Detail(c_id)
);
In this query, c_id in table Order_Detail is made as foriegn key, which is a reference
of c_id column in Customer_Detail table.
CHECK Constraint
CHECK constraint is used to restrict the value of a column between a range. It performs check
on the values, before storing them into the database. Its like condition checking before saving
data into a column.