National College of Computer Studies: Paknajol, Kathmandu
National College of Computer Studies: Paknajol, Kathmandu
Paknajol,Kathmandu
Example:
CREATE TABLE Student
(
Sid INTEGER(10) PRIMARY KEY,
Firstname VARCHAR(30) NOT NULL,
Lastname VARCHAR (30) NOT NULL
);
Description of example
Here, in the example above the Sid which is Integer data type is
primary key that means it must be a unique one, it shouldn’t be
repeated values. If we keep repeated value then SQL won’t accept it.
Similarly incase of Firstname and Lastname too the first name and
lastname of person which must be in character must not be a null
value that means it can’t be empty.
Some of the Constraints used in SQL
Some of the basic constraints which are used in SQL are as follows:
a. NOT NULL
It specifies that the column cannot store the
NULL value. Some value must be provided in
particular column.
b. UNIQUE
Specifies that each row for a column must have
a unique value. It works just like PRIMARY
key
c. FOREIGN KEY
Referential integrity of data in one table
to match value in the next table.
d. DEFAULT
Specifies the default value in the column.
The column specified as default will
assign the default value when the value is
empty
e. PRIMARY KEY
Used for uniquely identifying the tuples
(rows) in the relation of the database.
Each key must be unique one.
Why to Use Constraints in Database?
After being familiar with the constraints one question may come in
our mind why are we using the constraints? Well the answer to the
question may be by showing some uses of the constraints :
a. Protect Integrity of database
As constraints are the rules employed in database, it
helps in protecting the integrity of database. It allows only the
valid and accurate data maintain the integrity of database.
he values of individual columns are valid.
in a table, rows have a valid primary key or unique key values.
in a dependent table, rows have valid foreign key values that reference rows in a
parent table.
Integrity Constraints
Primary Key
(Table 2)
Dno D.location
10 Block A
11 Block B
12 Block C
Here in the above example there are two tables table 1 and table 2
where Eno is primary key and Dno is Foreign key in Table 1. The
record of Eno 3 is not allowded as Dno 14 is not defined as a primary
key of table 2 and in table 1 Dno is a foreign key defined. This record
cannot be referencing the D.location from table 2.
2. Entity Integrity Constraints
(Table 1)
www.tutorialspoint.com/sql/sql-constraints.htm
beginnersbook.com/2015/04/constraints-in-dbms/
www.w3schools.com/sql/sql_constraints.asp
http://www.edugrabs.com/types-of-constraints-in-dbms-or-
relational-constraints/
https://www.youtube.com/watch?v=zvYU9vlvDNY
https://en.wikipedia.org/wiki/Entity_integrity