Ensuring Data Integrity Through Constraints

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 26

Module 4

Ensuring Data Integrity


through Constraints

Module Overview
Enforcing Data Integrity
Implementing Domain Integrity
Implementing Entity and Referential Integrity

Lesson 1: Enforcing Data Integrity


Discussion: Data Integrity Across Application Layers
Types of Data Integrity
Options for Enforcing Data Integrity

Discussion: Data Integrity Across Application Layers


Consider these design issues:
Orders are placed only for customers that exist.
A rating column must contain an integer with a value

between 1 and 9.

A client code column must always contain a value.


Product specials must only be ordered on Tuesdays

during the summer period.

Should the application


enforce these rules?

Should the database


enforce these rules?

Types of Data Integrity


Domain Integrity
(Columns)

Entity Integrity
(Rows)

Referential Integrity
(Between Tables or Columns in
different rows of the same
Table)

Options for Enforcing Data Integrity


Mechanism

Description

Data types

Defines the type of data that can be stored


in a column

Nullability

Determines whether or not a value must be


present in a column

Constraints

Triggers

Defines rules that limit the values that might


be stored in a column or how values in
different columns in a table must be related.
A default value constraint defines the value
of a column if a value is not specified
Defines code that is executed automatically
when a table is modified

Earlier versions of SQL Server used Rules and Defaults as


separate objects. These should no longer be used.

Lesson 2: Implementing Domain Integrity


Data Types
Column Nullability
DEFAULT Constraints
CHECK Constraints
Demonstration 2A: Data and Domain Integrity

Data Types
Important decision when designing tables
Can be assigned using:

System Data Types

Alias Data Types

User-defined Data Types

CREATE
CREATE TABLE
TABLE Sales.Opportunity
Sales.Opportunity
(
(
OpportunityID
OpportunityID int
int NOT
NOT NULL,
NULL,
Requirements
Requirements nvarchar(50)
nvarchar(50) NOT
NOT NULL,
ReceivedDate
ReceivedDate date
date NOT
NOT NULL,
NULL,
LikelyClosingDate
LikelyClosingDate date
date NOT
NOT NULL,
NULL,
SalespersonID
SalespersonID int
int NOT
NOT NULL,
NULL,
Rating
Rating int
int NOT
NOT NULL
NULL
);
);

Column Nullability
Determines whether a value must be provided for a column
Allows you to specify the value explicitly as NULL in an INSERT
Is often inappropriately defined

CREATE
CREATE TABLE
TABLE Sales.Opportunity
Sales.Opportunity
(
(
OpportunityID
OpportunityID int NOT NULL,
Requirements
Requirements nvarchar(50)
nvarchar(50) NOT
NOT NULL,
NULL,
ReceivedDate
ReceivedDate date
date NOT
NOT NULL,
NULL,
LikelyClosingDate
LikelyClosingDate date
date NULL,
NULL,
SalespersonID
SalespersonID int NULL,
Rating
Rating int
int NOT
NOT NULL
NULL
);
);

DEFAULT Constraints
Provide default values for columns
Are used when no value is provided in an INSERT statement
Must be compatible with the data type for the column

CREATE TABLE
TABLE Sales.Opportunity
Sales.Opportunity
(
OpportunityID int
int NOT
NOT NULL,
NULL,
Requirements nvarchar(50)
nvarchar(50) NOT
NOT NULL,
NULL,
ReceivedDate date
date
CONSTRAINT
CONSTRAINT DF_Opportunity_ReceivedDate
DF_Opportunity_ReceivedDate
DEFAULT
DEFAULT (SYSDATETIME())
(SYSDATETIME()) NOT
NOT NULL,
NULL,
LikelyClosingDate date
date NOT
NOT NULL,
NULL,
SalespersonID int
int NOT
NOT NULL,
NULL,
Rating int
int NOT
NOT NULL
NULL
);
);

CHECK Constraints
Limits the values that are accepted into a column
Values that evaluate to FALSE are rejected
Care must be taken with nullable columns
Can be defined at table level to refer to multiple columns
CREATE
CREATE TABLE
TABLE Sales.Opportunity
Sales.Opportunity
((
OpportunityID
OpportunityID int
int NOT
NOT NULL,
NULL,
Requirements
Requirements nvarchar(50)
nvarchar(50) NOT
NOT NULL,
NULL,
ReceivedDate
ReceivedDate date
date NOT
NOT NULL,
NULL,
LikelyClosingDate
LikelyClosingDate date
date NOT
NOT NULL,
NULL,
SalespersonID
SalespersonID int
int NOT
NOT NULL,
NULL,
Rating
Rating int
int
CONSTRAINT
CONSTRAINT CHK_Opportunity_Rating_Range1To4
CHK_Opportunity_Rating_Range1To4
CHECK
CHECK (Rating
(Rating BETWEEN
BETWEEN 11 AND
AND 4)
4) NOT
NOT NULL
NULL
);
);

Demonstration 2A: Data and Domain Integrity


In this demonstration, you will see how to enforce data and
domain integrity

Lesson 3: Implementing Entity and Referential


Integrity
PRIMARY KEY Constraints
UNIQUE Constraints
FOREIGN KEY Constraints
Cascading Referential Integrity
Considerations for Constraint Checking
Demonstration 3A: Entity and Referential Integrity
IDENTITY Property
Sequences
Demonstration 3B: Working with Sequences

PRIMARY KEY Constraints


Is used to uniquely identify a row in a table
Must be unique and not NULL
May involve multiple columns

CREATE TABLE
TABLE Sales.Opportunity
Sales.Opportunity
(
OpportunityID int
int NOT
NOT NULL
NULL
CONSTRAINT
CONSTRAINT PK_Opportunity
PK_Opportunity
PRIMARY
PRIMARY KEY,
KEY,
Requirements nvarchar(50)
nvarchar(50) NOT
NOT NULL,
NULL,
ReceivedDate date
date NOT
NOT NULL,
NULL,
LikelyClosingDate date
date NULL,
NULL,
SalespersonID int
int NULL,
NULL,
Rating int
int NOT
NOT NULL
NULL
);
);

UNIQUE Constraints
Requires that values in each row are different if supplied
Must be unique but one row can be NULL
May involve multiple columns
CREATE
CREATE TABLE
TABLE Sales.Opportunity
Sales.Opportunity
((
OpportunityID
OpportunityID int
int NOT
NOT NULL
NULL
CONSTRAINT
CONSTRAINT PK_Opportunity
PK_Opportunity
PRIMARY
PRIMARY KEY,
KEY,
Requirements
Requirements nvarchar(50)
nvarchar(50) NOT
NOT NULL
NULL
CONSTRAINT
CONSTRAINT UQ_Opportunity_Requirements
UQ_Opportunity_Requirements
UNIQUE,
UNIQUE,
ReceivedDate
ReceivedDate date
date NOT
NOT NULL,
NULL,
LikelyClosingDate
LikelyClosingDate date
date NULL,
NULL,
SalespersonID
SalespersonID int
int NULL,
NULL,
Rating
Rating int
int NOT
NOT NULL
NULL
);
);

FOREIGN KEY Constraints


Is used to enforce relationships between tables
Must reference PRIMARY KEY or UNIQUE column(s)
May be NULL
Can be applied WITH NOCHECK
CREATE
CREATE TABLE
TABLE Sales.Opportunity
Sales.Opportunity
((
OpportunityID
OpportunityID int
int NOT
NOT NULL
NULL
CONSTRAINT
CONSTRAINT PK_Opportunity
PK_Opportunity
PRIMARY
PRIMARY KEY,
KEY,
Requirements
Requirements nvarchar(50)
nvarchar(50) NOT
NOT NULL,
NULL,
ReceivedDate
ReceivedDate date
date NOT
NOT NULL,
NULL,
LikelyClosingDate
LikelyClosingDate date
date NULL,
NULL,
SalespersonID
SalespersonID int
int NULL
NULL
CONSTRAINT
CONSTRAINT FK_Opportunity_Salesperson
FK_Opportunity_Salesperson
FOREIGN
FOREIGN KEY
KEY
REFERENCES
REFERENCES Sales.Salesperson
Sales.Salesperson (BusinessEntityID),
(BusinessEntityID),
Rating
Rating int
int NOT
NOT NULL
NULL
);
);

Cascading Referential Integrity


Controlled
Controlled by
by CASCADE
CASCADE clause
clause of
of FOREIGN
FOREIGN KEY
KEY

Option
NO ACTION
(default)
CASCADE

UPDATE Behavior

DELETE behavior

Return error and roll back operation


Update foreign keys in
referencing tables

Delete rows in
referencing table

SET NULL

Set foreign keys in referencing tables to NULL

SET
DEFAULT

Set foreign keys in referencing tables to DEFAULT


values

Considerations for Constraint Checking


Assign meaningful names to constraints
Create, change, and drop constraints without having

to drop and recreate the table

Perform error checking in your applications and

transactions

Disable CHECK and FOREIGN KEY constraints:

To improve performance during large batch jobs

To avoid checking existing data when you add new


constraints to a table

Demonstration 3A: Entity and Referential Integrity


In this demonstration, you will see how to define:
Entity integrity for tables
Referential integrity for tables
Cascading referential integrity constraints

IDENTITY Property
Property of a column
Specify a seed and an increment
Default seed and increment are both 1
SCOPE_IDENTITY(), @@IDENTITY
CREATE
CREATE TABLE
TABLE Sales.Opportunity
Sales.Opportunity
((
OpportunityID
OpportunityID int
int NOT
NOT NULL
NULL
IDENTITY(1,1),
IDENTITY(1,1),
Requirements
Requirements nvarchar(50)
nvarchar(50) NOT
NOT NULL,
NULL,
ReceivedDate
ReceivedDate date
date NOT
NOT NULL,
NULL,
LikelyClosingDate
LikelyClosingDate date
date NULL,
NULL,
SalespersonID
SalespersonID int
int NULL,
NULL,
Rating
Rating int
int NOT
NOT NULL
NULL
);
);

Sequences
Are user-defined schema-bound objects
Are not tied to any particular table
Can be used to ease migration from other database engines

CREATE SEQUENCE
SEQUENCE Booking.BookingID
Booking.BookingID AS
AS INT
INT
START
START WITH
WITH 20001
20001
INCREMENT
INCREMENT BY
BY 10;
10;
CREATE TABLE
TABLE Booking.FlightBooking
Booking.FlightBooking
( FlightBookingID
FlightBookingID INT
INT NOT
NOT NULL
NULL PRIMARY
PRIMARY KEY
KEY
CLUSTERED
CLUSTERED
DEFAULT
DEFAULT (NEXT VALUE
VALUE FOR
FOR Booking.BookingID),
Booking.BookingID),
...
...

Demonstration 3B: Working with Identity and


Sequences
In this demonstration, you will see how to:
Work with identity constraints
Create a sequence
Use a sequence to provide key values for two tables

Lab 4: Ensuring Data Integrity through Constraints


Exercise 1: Constraint Design
Challenge Exercise 2: Test the constraints (Only if time

permits)

Logon information

Virtual machine

10776A-MIA-SQL1

User name

AdventureWorks\Administrator

Password

Pa$$w0rd

Estimated time: 45 minutes

Lab Scenario
A table has recently been added to the Marketing system
but has no constraints in place. In this lab, you will
implement the required constraints to ensure data integrity.
You have been supplied with the required specifications of a
new table called Marketing.Yield. You need to implement
the required constraints and, if you have time, test their
behavior.

Lab Review
In SQL Server Management Studio, you successfully ran a

script that created a table but you dont see the table in
Object Explorer. What do you need to do?

What does the option Default do when creating a column?


What requirement does a primary key constraint have that

a unique constraint doesnt?

Module Review and Takeaways


Review Questions
Best Practices

You might also like