0% found this document useful (0 votes)
0 views22 pages

Constrains

The document outlines the various types of constraints in Microsoft SQL Server, including primary key, foreign key, unique, check, default, and not null constraints, which help enforce data integrity and validation in tables. Constraints can be defined at the column or table level and can be added during table creation or modified later. It also explains how to disable and drop constraints, as well as how to view existing constraints on a table.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views22 pages

Constrains

The document outlines the various types of constraints in Microsoft SQL Server, including primary key, foreign key, unique, check, default, and not null constraints, which help enforce data integrity and validation in tables. Constraints can be defined at the column or table level and can be added during table creation or modified later. It also explains how to disable and drop constraints, as well as how to view existing constraints on a table.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Constraints

 Microsoft SQL Server allows you to specify


constraints of various types on tables, so
that the database engine itself can handle
various types of validations automatically.
 For example, you can create a primary key
constraint on a table to ensure uniqueness
of key values. Similarly, you can use check
constraint to limit the possible values for
field or a group of fields.
Constraints
 Constraints can be specified in two ways:
Column constraint and Table constraint.
 Column Level:
 A column constraint is linked to specify
column in a table, while a table
 Constraint can refer to one or more columns
within a table. In a
 CREATE TABLE statement, a column
constraint is specified along with the name
of the column that refers to.
Constraints
 Table Level:
 while a table constraint is given after all
the column specifications have been
given.
 Constraints can be explicitly named by
us, or may be kept unnamed, in which
case SQL Server assigns a unique name
to the constraint.
Types of Constraints
 Constraints can be specified when a
table is created (with the CREATE TABLE
statement) or after the table is created
(with the ALTER TABLE statement).
 NOT NULL
 DEFAULT
 CHECK
 UNIQUE
 PRIMARY KEY
 FOREIGN KEY
Types of Keys
 NOT NULL:
 The NOT NULL constraint enforces a column to NOT
accept NULL values.
 The NOT NULL constraint enforces a field to always

contain a value. Or
 NOT NULL constraint on a column is used to tell the

database that a value must always be specified for


that column; it cannot be null
CREATE TABLE EmployeeDetails
(
EmployeeID CHAR(1) NOT NULL
)
Types of Keys
 If you want to allow a null value for a column, you
must use the NULL clause instead.
 For example:
 CREATE TABLE EmployeeDetails
 (
 EmployeeID CHAR(1) NULL
 )
 NOTE: The default in SQL Server is NULL, though
the ANSI standard is NULL.
Types of Keys
 DEFAULT Constraint:
 The DEFAULT constraint is used to insert a
default value into a column.
 The default value will be added to all new
records, if no other value is specified. Or
 A default constraint allows you to specify a
default value for a column if no value is
specified for that column while inserting a
new row.
Types of Keys
 DEFAULT Constraint:
CREATE TABLE EmployeeDetails
(
EmpID INT,
EmpName VARCHAR(50),
Gender CHAR(1) DEFAULT('F')
)
GO

INSERT EmployeeDetails(EmpID, EmpName) VALUES(1,'Employee_1')


GO

SELECT *
FROM EmployeeDetails
GO
Types of Keys
 CHECK Constraint:
 A check constraint implement domain integrity, i.e., rules that govern
what the valid entries are in a table.
 CHECK constraints limiting the values that are accepted by a column.
 If you define a CHECK constraint on a single column it allows only
certain values for this column.
 Ex: in an employee table, you may not want the employee age to be
less than 18 years or more than 65 years
 CHECK constraint get executed when new record is inserted or to
update existing record.
 A CHECK constraint returns TRUE when the condition is satisfied if it
is not it returns FALSE
 When CHECK constraint returns TRUE only record inserted or
updated.
 You can apply multiple CHECK constraints to a single column.
 You can also apply a single CHECK constraint to multiple columns
Types of Keys
CREATE TABLE EmployeeDetails
(
EmpId INT,
Age TINYINT,
EmpName VARCHAR(50),
CONSTRAINT employee_ck01 CHECK (Age BETWEEN 18
AND 65)
)

Inserting records with valid age


INSERT INTO EmployeeDetails VALUES(1,21,'Employee1')

Inserting records with invalid age


INSERT INTO EmployeeDetails VALUES(1,17,'Employee1')
Types of Keys
 Primary Key:
 The PRIMARY KEY constraint uniquely
identifies each record in a database table.
 A primary key constraint specifies that a field
or group of fields in a table should have
unique, non-null values.
 To uniquely identify a row, Primary key is
used.
 Primary Key can not allow duplicate values
and null values.
 A table allows only one Primary key
Types of Keys
 CREATE TABLE Department
 (
 Dept_Code CHAR(4) CONSTRAINT dept_pk PRIMARY KEY,
 Dept_Name CHAR(2)
 )
 GO

 CREATE TABLE Department


 (
 Dept_Code CHAR(4),
 Dept_Name CHAR(2),
 CONSTRAINT dept_pk1 PRIMARY KEY(Dept_Code)
 )
 GO
Types of Keys
 CREATE TABLE InvoiceDetails
 (
 Invoice_Year NUMERIC(4),
 Invoice_Number Numeric(5),
 Customer_Code CHAR(4),
 -- More columns to be added here
 CONSTRAINT invoice_pk PRIMARY KEY(Invoice_Year, Invoice_Number)
 )
 CREATE TABLE Department
 (
 Dept_Code CHAR(4) NOT NULL,
 Dept_Name CHAR(2)
 )
 GO
 ALTER TABLE Department ADD CONSTRAINT dept_pk PRIMARY KEY(Dept_Code)
 Go
Types of Keys
 UNIQUE KEY
 The UNIQUE constraint uniquely identifies each record in
a database table.
 A unique constraint is similar to a primary key constraint
 The UNIQUE and PRIMARY KEY constraints both provide
uniqueness for a column or set of columns.
 UNIQUE constraints allow one null value per column.
 A table allows multiple Unique constraints.
 There is one small difference a primary key expression
cannot have a null value, a unique constraint expression
can.
 A UNIQUE constraint can be referenced by a FOREIGN
KEY constraint.
Types of Keys
CREATE TABLE EmployeeDetails
(
EmpID INT,
EmpName VARCHAR(30),
PassportNumber CHAR(20),
CONSTRAINT Employee_Unique UNIQUE(PassportNumber)
)
GO
INSERT INTO EmployeeDetails VALUES(1,'Employee1','B120987')
INSERT INTO EmployeeDetails VALUES(2,'Employee2','B134821')
GO
Inserting same passport number as Employee1
INSERT INTO EmployeeDetails VALUES(3,'Employee3','B120987')
GO
Types of Keys
 Foreign Key :
 In a typical database, various tables have some logical relationship
between themselves; a database is not just a group of unrelated
tables. In most such databases, certain referential integrity
relationship must exist between tables; otherwise logically the
data would be corrupt.
 To make relation between tables we used Foreign key.
 A Foreign key in a table is referred another table’s primary key or
Unique.
 A Primary key can be referred by multiple foreign keys from other
tables.
 SQL Server enforces referential integrity through the use of foreign
key constraint.
 a Foreign key can refer back to the same table but to a different
column. This kind of foreign key is known as “self-referencing
foreign key”.
Types of Keys
CREATE TABLE Department
(
Dept_Code CHAR(4),
Dept_Name VARCHAR(50),
CONSTRAINT dept_pk PRIMARY KEY(Dept_Code)
)
GO
CREATE TABLE EmployeeDetails
(
EmpID INT,
EmpName CHAR(30),
Dept_Code CHAR(4),
CONSTRAINT employee_fk01 FOREIGN KEY (Dept_Code)
REFERENCES Department(Dept_Code)
)
GO
Types of Keys
Foreign key constraint with
 ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT }

 ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT }

CREATE TABLE EmployeeDetails


(
EmpID INT,
EmpName CHAR(30),
Dept_Code CHAR(4),
CONSTRAINT employee_fk01 FOREIGN KEY (Dept_Code)
REFERENCES Department(Dept_Code)
ON DELETE CASCADE
ON UPDATE CASCADE
)
 GO
Types of Keys
Deleting department records where department code
is DPT4
DELETE FROM Department
WHERE Dept_Code = 'DEP4'
GO

Updating department records where department


code is DEP1
UPDATE Department
SET Dept_Code = 'DPT5'
WHERE Dept_Code = 'DEP1'
GO
Disabling a constraint
CREATE TABLE dbo.cnst_example
(
id INT NOT NULL,
name VARCHAR(10) NOT NULL,
salary MONEY NOT NULL
CONSTRAINT salary_cap CHECK (salary < 100000)
)
GO
Valid inserts
INSERT INTO dbo.cnst_example VALUES (1,'Joe Brown',65000);
INSERT INTO dbo.cnst_example VALUES (2,'Mary Smith',75000);
This insert violates the constraint.
INSERT INTO dbo.cnst_example VALUES (3,'Pat Jones',105000);
Disable the constraint and try again.
ALTER TABLE dbo.cnst_example NOCHECK CONSTRAINT salary_cap;
INSERT INTO dbo.cnst_example VALUES (3,'Pat Jones',105000);
Re-enable the constraint and try another insert; this will fail.
ALTER TABLE dbo.cnst_example CHECK CONSTRAINT salary_cap;
INSERT INTO dbo.cnst_example VALUES (4,'Eric James',110000) ;
Dropping a Constraint
CREATE TABLE dbo.doc_exc
(
column_a INT
CONSTRAINT my_constraint UNIQUE
)
GO

ALTER TABLE dbo.doc_exc DROP CONSTRAINT


my_constraint ;
GO
View Constraint
To view the list of constraints on table, you
can give the following command:
Syntax:
[ EXECUTE | EXEC ] sp_helpconstraint
<table_name>
Example:
EXEC sp_helpconstraint 'Department'
GO

You might also like