Anda di halaman 1dari 5

CONSTRAINTS

A constraint is a property assigned to a column or the set of columns in a table that prevents to inconsistent values in
the column(s) and ensures the accuracy and reliability of the data in the database . Constraints are used to enforce
the data integrity. The following categories of the data integrity exist:
 Entity Integrity ensures that there are no duplicate rows in a table.
 Domain Integrity enforces valid entries for a given column by restricting the type, the format, or the range of
possible values.
 Referential integrity ensures that rows cannot be deleted, which are used by other records (for example,
corresponding data values between tables will be vital).
 User-Defined Integrity enforces some specific business rules that do not fall into entity, domain, or referential
integrity categories.

Each of these categories of the data integrity can be enforced by the appropriate constraints. Microsoft SQL Server supports the
following constraints:
1. PRIMARY KEY constraints
2. UNIQUE constraints
3. FOREIGN KEY constraints
4. CHECK constraints
5. NOT NULL constraints
6. DEFAULT constraints

1- PRIMARY KEY CONSTRAINTS


A PRIMARY KEY constraint is a unique identifier for a row within a table and only one primary key constraint
can be created in a table. The primary key constraints are used to enforce entity integrity.
i. Create table Statement  to create Primary Key
a. Column Level
Example:
CREATE TABLE Products
(
ProductID INT CONSTRAINT pk_On_pid PRIMARY KEY,
ProductName VARCHAR(25)
);
b.Table Level
Example:
CREATE TABLE Products
(
ProductID INT,
ProductName VARCHAR(25)
CONSTRAINT pk_products_pid PRIMARY KEY(ProductID)
);
c. Add a constraint to an existing table
Example:
ALTER TABLE Products
ADD CONSTRAINT pk_On_pid PRIMARY KEY(ProductID)

ii. Alter table Statement to Drop Primary key


Example:
ALTER TABLE Products DROP CONSTRAINT;

2- UNIQUE KEY CONSTRAINTS


Unique Constraints to make sure that no duplicate values are entered in specific columns and UNIQUE
constraints allow single value NULL in specific column. By default its create NonCluster index.
i. Create table Statement  to create Unique Key
A.Column Level
Example:
create table t_test

1
(
aid int CONSTRAINT u_aid unique,
aName varchar(50)
)
B.Table Level
Example:
create table t_test
(
aid int ,
aName varchar(50),
More than one
CONSTRAINT u_aid unique(aid),
unique
CONSTRAINT u_aName unique(aName) constraint
)
C. Add a constraint to an existing table
Example:
ALTER TABLE T_TEST
ADD CONSTRAINT u_aid unique(aid)

ii. Alter table Statement to Drop Unique key


Example:
ALTER TABLE T_TEST DROP CONSTRAINT u_aid

3- FOREIGN KEY CONSTRAINTS


When we add a Foreign key to the table, we are creating a dependency between the table for which we define the Foreign
key (the referencing table) and the table your Foreign key references (the referenced table).Once we have set up a foreign
key for a table, any record inserted into the referencing table must either have a matching record in the referenced
column(s) of the referenced table, or the value of the foreign key column must be set to NOTNULL.
i. Create table Statement  to create Foreign Key
a. Column Level
Example:
CREATE TABLE ProductSales
(
SalesID INT CONSTRAINT pk_productSales_sid PRIMARY KEY,
ProductID INT CONSTRAINT fk_productSales_pid FOREIGN KEY REFERENCES
Products(ProductID),
SalesPerson VARCHAR(25)
);
b.Table Level
Example:
CREATE TABLE ProductSales
(
SALESID INT,
PRODUCTID INT,
SALESPERSON VARCHAR(25),
CONSTRAINT PK_PRODUCTSALES_SID PRIMARY KEY(SALESID),
CONSTRAINT FK_PRODUCTSALES_PID FOREIGN KEY(PRODUCTID)REFERENCES
PRODUCTS(PRODUCTID)
)
c. Add a constraint to an existing table
Example:
ALTER TABLE ProductSales
ADD CONSTRAINT fk_productSales_pid
FOREIGN KEY(ProductID)REFERENCES Products(ProductID)
ii. Alter table Statement to Drop Foreign key
Example:
ALTER TABLE ProductSales DROP CONSTRAINT fk_productSales_pid;

2
4- CHECK CONSTRAINTS
They are similar to FOREIGN KEY constraints in that they control the values that are put in a column. You can create
a CHECK constraint with any logical (Boolean) expression that returns TRUE or FALSE based on the logical operators. The
check constraints are used to enforce domain integrity.

 Note: - In a foreign key validates data from another table but in a check constraint validate data in a column values.

i. Create table Statement  to create CHECK constraint


a. Column Level
Example:
CREATE TABLE Products_2
(
ProductID int PRIMARY KEY,
UnitPrice money CHECK(UnitPrice > 0 AND UnitPrice < 100)
)
b.Table Level
Example:
CREATE TABLE Products_2
(
ProductID int PRIMARY KEY,
UnitPrice money,
CONSTRAINT CK_UnitPrice2 CHECK(UnitPrice > 0 AND UnitPrice < 100)
)
c. Add a constraint to an existing table
Example:
ALTER TABLE PRODUCTS_2 WITH NOCHECK
ADD CONSTRAINT CK_UNITPRICE2 CHECK(UNITPRICE > 0 AND UNITPRICE < 100)
d.Check constraints and existing values
CHECK constraint after a table is populated runs a chance of failure, because the database will check
existing data for conformance. But it is possible to avoid the conformance test when adding a CHECK
constraint using WITH NOCHECK.
Example:
CREATE TABLE Employees_2
(
EmployeeID int,
Salary money
)
INSERT INTO Employees_2 VALUES(1, -1)

ALTER TABLE Employees_2 WITH NOCHECK


ADD CONSTRAINT CK_Salary CHECK(Salary > 0)
e. Check constraints and NULL value
Earlier in this section we mentioned how the database will only stop a data modification when a check restraint
returns false. We did not mention, however, how the database allows the modification to take place if the result is
logically unknown. A logically unknown expression happens when a NULL value is present in an expression. For
example, let’s use the following insert statement on the last table created above.

INSERT INTO Employees_2 (EmployeeID , Salary) VALUES(2, NULL)

Even with the constraint on salary (Salary > 0) in place, the INSERT is successful. A NULL value makes the
expression logically unknown. A CHECK constraint will only fail an INSERT or UPDATE if the expression in
the constraint explicitly returns false. An expression returning true, or a logically unknown expression will
let the command succeed.

f. Restrictions on check constraints


Although check constraints are by far the easiest way to enforce domain integrity in a database, they do have
some limitations, namely:
o A check constraint cannot reference a different row in a table.
o A check constraint cannot reference a column in a different table.

g. Disable/ enable check constraints in the table


3
Example 1:
-- disable the check_sale constraint in the employee table
ALTER TABLE employee NOCHECK CONSTRAINT check_sale
Example 2:
-- enable the check_sale constraint in the employee table
ALTER TABLE employee CHECK CONSTRAINT check_sale

If you need to disable all of the constraints on a table


ALTER TABLE PRODUCTS NOCHECK CONSTRAINT ALL

ii. Alter table Statement to Drop CHECK constraints.


Example:
ALTER TABLE PRODUCTS_2
DROP CONSTRAINT CK_UNITPRICE2;

5- NOT NULL CONSTRAINTS


A NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to
enforce domain integrity
i. Create table Statement  to create NOT NULL
A.Column Level
Example:
CREATE TABLE employee
(
EmployeeId INT NOT NULL,
LName VARCHAR(30) NOT NULL,
FName VARCHAR(30) NOT NULL,
HireDate DATETIME NOT NULL
)
B.Table Level
Example:
CREATE TABLE employee
(
EmployeeId INT ,
LName VARCHAR(30),
FName VARCHAR(30) NOT NULL,
HireDate DATETIME NOT NULL,
constraint NN_Lname check(fname is NOT NULL)
)
C. Add a constraint to an existing table
Example 1:
ALTER TABLE employee
ADD constraint NN_Lname check(fname is NOT NULL)
Example 2:
ALTER TABLE employee WITH NOCHECK
ADD constraint NN_Lname check(fname is NOT NULL)

ii. Alter table Statement to Drop NOT NULL


Example:
ALTER TABLE T_TEST DROP CONSTRAINT u_ Lname

6- DEFAULT CONSTRAINTS
4
Each column in a record must contain a value, even if that value is NULL. If a column does not allow for null
values and does not have a DEFAULT definition, you must explicitly specify a value for the column, or the Database
Engine returns an error that states that the column does not allow null values.
i. Create table Statement to create DEFAULT.
a. Column Level
Example:
CREATE TABLE employee
(
EmployeeId INT ,
Name VARCHAR(30),
HireDate DATETIME NOT NULL default getdate()
)
b.Table Level
Example:
CREATE TABLE employee
(
EmployeeId INT ,
Name VARCHAR(30),
HireDate DATETIME NOT NULL
constraint HireDate default getdate()
)
c. Add a constraint to an existing table
Example 1:
alter table employee
add constraint d_HireDate default getdate() for HireDate
Example 2:
alter table employee
alter column HireDate default getdate()

ii. Alter table Statement to Drop DEFAULT.


Example:
ALTER TABLE employee DROP CONSTRAINT d_HireDate

Anda mungkin juga menyukai