Programming Microsoft SQL
Server
03 - Constraints
Constraints Types
Domain Integrity
(Columns)
Entity Integrity
(Rows)
Referential Integrity
(Between Tables or Columns of the Same Table)
What Are Constraints?
Integrity
type
Constraint
type
Description
Domain
DEFAULT Specifies default value for column
CHECK Specifies allowed value for column
FOREIGN KEY Specifies column in which values must exist
NULL Specifies whether NULL is permitted
Entity
PRIMARY KEY Identifies each row uniquely
UNIQUE Prevents duplication of nonprimary keys
Referential
FOREIGN KEY
Defines columns whose value must match the primary key of
this table
CHECK
Specifies the allowed value for a column based on the
contents of another column
Constraint Scope
CREATE TABLE [dbo].[Customers] (
[CustomerID] [int] IDENTITY (1, 1) NOT NULL PRIMARY KEY ,
[CustomerEmail] [varchar] (30) NULL ,
[CustomerState] [varchar] (5) NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Products] ADD
CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED
(
[ProductID],
[ProductName]
) ON [PRIMARY]
GO
• Column Level
• Table Level
PRIMARY KEY Constraints
 PRIMARY KEY constraints identify one or
more columns in a table that constitute a
primary key
 One PRIMARY KEY constraint is allowed per
table
 Value must be unique across constituent
columns
 Null values are not allowed in constituent
columns
PRIMARY KEY Constraints
CREATE TABLE [dbo].[DEPARTMENTS](
[DNO] [int] IDENTITY(1,1) PRIMARY KEY,
[DNAME] [nvarchar](20) NULL
) ON [PRIMARY]
CREATE TABLE [HumanResources].[Department](
[DepartmentID] [smallint] IDENTITY(1,1) NOT NULL,
[Name] [dbo].[Name],
…
CONSTRAINT [PK_Department_DepartmentID] PRIMARY KEY CLUSTERED
([DepartmentID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON
[PRIMARY]
)
Default Constraints
 DEFAULT constraints define a default column
value when no value is provided
 Only one DEFAULT constraint per column
 Only applicable to INSERT statements
 Some system supplied functions allowed
CREATE TABLE [Production].[Location](
...
[Availability] [decimal](8, 2) NOT NULL CONSTRAINT
[DF_Location_Availability] DEFAULT (0.00),
[ModifiedDate] [datetime] NOT NULL CONSTRAINT
[DF_Location_ModifiedDate] DEFAULT (getdate())
)
Check Constraints
 CHECK constraints restrict the values that can
be entered into a column on INSERT or
UPDATE.
 Can define multiple CHECK constraints per
column.
 Can reference columns in the same table.
 Cannot contain subqueries.
ALTER TABLE [HumanResources].[EmployeeDepartmentHistory]
WITH CHECK
ADD CONSTRAINT [CK_EmployeeDepartmentHistory_EndDate] CHECK
(([EndDate]>=[StartDate] OR [EndDate] IS NULL))
Disabling Constraints
 Bad Data During Constraint Creation?
ALTER TABLE [dbo].[Products]
WITH NOCHECK
ADD CONSTRAINT [CK_Products_No_Nissan]
CHECK ([Productname] <> 'nissan sentra')
 Temporarily During Data Load
ALTER TABLE Products
NOCHECK
CONSTRAINT CK_Products_No_Nissan
UNIQUE Constraint
 UNIQUE constraints ensure that every value in a
column is unique
 Only one null value allowed in a unique column
 Can include one or more columns
CREATE TABLE [HumanResources].[Employee](
[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
[NationalIDNumber] [nvarchar](15) NOT NULL UNIQUE
NONCLUSTERED,
…
)
FOREIGN KEY Constraints
 FOREIGN KEY constraints ensure referential
integrity between columns in same or
different tables
 Must reference a PRIMARY KEY or UNIQUE
constraint
 User must have REFERENCES permission on
referenced table
ALTER TABLE [Sales].[SalesOrderHeader] WITH CHECK
ADD CONSTRAINT
[FK_SalesOrderHeader_Customer_CustomerID]
FOREIGN KEY([CustomerID])
REFERENCES [Sales].[Customer] ([CustomerID])
Considerations for Constraint Checking
 Assign meaningful names to constraints
 Create, change, and drop constraints without
having to drop and re-create the table
 Perform error checking in your applications
and transactions
 Disable CHECK and FOREIGN KEY
constraints:
 To improve performance when you run large
batch jobs
 To avoid checking existing data when you add
new constraints to a table
Other Data Integrity Methods
 Triggers
 Good for non-normalized data
 Procedural
 No inserts allowed, only use of Stored Procs that
perform the insert/update/delete after checking data
 Can perform modifications in more than one table
 Application Role
 Client application gets hard coded password
 Updates only allowed through that application

03Constraints - last.pdf

  • 1.
  • 2.
    Constraints Types Domain Integrity (Columns) EntityIntegrity (Rows) Referential Integrity (Between Tables or Columns of the Same Table)
  • 3.
    What Are Constraints? Integrity type Constraint type Description Domain DEFAULTSpecifies default value for column CHECK Specifies allowed value for column FOREIGN KEY Specifies column in which values must exist NULL Specifies whether NULL is permitted Entity PRIMARY KEY Identifies each row uniquely UNIQUE Prevents duplication of nonprimary keys Referential FOREIGN KEY Defines columns whose value must match the primary key of this table CHECK Specifies the allowed value for a column based on the contents of another column
  • 4.
    Constraint Scope CREATE TABLE[dbo].[Customers] ( [CustomerID] [int] IDENTITY (1, 1) NOT NULL PRIMARY KEY , [CustomerEmail] [varchar] (30) NULL , [CustomerState] [varchar] (5) NULL ) ON [PRIMARY] GO ALTER TABLE [dbo].[Products] ADD CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED ( [ProductID], [ProductName] ) ON [PRIMARY] GO • Column Level • Table Level
  • 5.
    PRIMARY KEY Constraints PRIMARY KEY constraints identify one or more columns in a table that constitute a primary key  One PRIMARY KEY constraint is allowed per table  Value must be unique across constituent columns  Null values are not allowed in constituent columns
  • 6.
    PRIMARY KEY Constraints CREATETABLE [dbo].[DEPARTMENTS]( [DNO] [int] IDENTITY(1,1) PRIMARY KEY, [DNAME] [nvarchar](20) NULL ) ON [PRIMARY] CREATE TABLE [HumanResources].[Department]( [DepartmentID] [smallint] IDENTITY(1,1) NOT NULL, [Name] [dbo].[Name], … CONSTRAINT [PK_Department_DepartmentID] PRIMARY KEY CLUSTERED ([DepartmentID] ASC) WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] )
  • 7.
    Default Constraints  DEFAULTconstraints define a default column value when no value is provided  Only one DEFAULT constraint per column  Only applicable to INSERT statements  Some system supplied functions allowed CREATE TABLE [Production].[Location]( ... [Availability] [decimal](8, 2) NOT NULL CONSTRAINT [DF_Location_Availability] DEFAULT (0.00), [ModifiedDate] [datetime] NOT NULL CONSTRAINT [DF_Location_ModifiedDate] DEFAULT (getdate()) )
  • 8.
    Check Constraints  CHECKconstraints restrict the values that can be entered into a column on INSERT or UPDATE.  Can define multiple CHECK constraints per column.  Can reference columns in the same table.  Cannot contain subqueries. ALTER TABLE [HumanResources].[EmployeeDepartmentHistory] WITH CHECK ADD CONSTRAINT [CK_EmployeeDepartmentHistory_EndDate] CHECK (([EndDate]>=[StartDate] OR [EndDate] IS NULL))
  • 9.
    Disabling Constraints  BadData During Constraint Creation? ALTER TABLE [dbo].[Products] WITH NOCHECK ADD CONSTRAINT [CK_Products_No_Nissan] CHECK ([Productname] <> 'nissan sentra')  Temporarily During Data Load ALTER TABLE Products NOCHECK CONSTRAINT CK_Products_No_Nissan
  • 10.
    UNIQUE Constraint  UNIQUEconstraints ensure that every value in a column is unique  Only one null value allowed in a unique column  Can include one or more columns CREATE TABLE [HumanResources].[Employee]( [EmployeeID] [int] IDENTITY(1,1) NOT NULL, [NationalIDNumber] [nvarchar](15) NOT NULL UNIQUE NONCLUSTERED, … )
  • 11.
    FOREIGN KEY Constraints FOREIGN KEY constraints ensure referential integrity between columns in same or different tables  Must reference a PRIMARY KEY or UNIQUE constraint  User must have REFERENCES permission on referenced table ALTER TABLE [Sales].[SalesOrderHeader] WITH CHECK ADD CONSTRAINT [FK_SalesOrderHeader_Customer_CustomerID] FOREIGN KEY([CustomerID]) REFERENCES [Sales].[Customer] ([CustomerID])
  • 12.
    Considerations for ConstraintChecking  Assign meaningful names to constraints  Create, change, and drop constraints without having to drop and re-create the table  Perform error checking in your applications and transactions  Disable CHECK and FOREIGN KEY constraints:  To improve performance when you run large batch jobs  To avoid checking existing data when you add new constraints to a table
  • 13.
    Other Data IntegrityMethods  Triggers  Good for non-normalized data  Procedural  No inserts allowed, only use of Stored Procs that perform the insert/update/delete after checking data  Can perform modifications in more than one table  Application Role  Client application gets hard coded password  Updates only allowed through that application