Sei sulla pagina 1di 19

SQL Server Table Constraints

http://mssqlsolutions.blogspot.com

Constraints
1.

2.
3.
4.
5.
6.

Primary Key
Foreign Key
Unique
Check
Default
Allow Nulls/Not Null

Primary Key (PK)


Primary key is based upon two rules,

1. Not Null
2. No duplicates
Can be a single column or set of columns that uniquely
identify a row in table.
Can not have NULL value.
Only one (1) Primary Key per table.
If it is used as a Foreign key (FK) constraint in any other
table, first delete FK constraint before deleting PK.
To modify existing PK, first delete existing PK and then
re-create new one.

Implementing PK
by SSMS
Open Table in design mode, select columns favorable for PKs, right click on them and apply
Set Primary Key option.

Unique Constraint
Enforces uniqueness of the values in a set of columns

Allow NULL values


Multiple unique constraints can be defined.
Can be used as Foreign Key constraint.
To modify existing Unique constraint, first delete it and

then re-create new one.

Implementing Unique Key


by SSMS
Step1 - Open Table in design mode, right click on any column and choose Indexes/Keys
option.

Implementing Unique Key


by SSMS

Step2 -

Foreign Key (FK)


It is a link between two tables (Master and Detail).

Based on a column or set of columns


Can refer Primary key or Unique key.
Multiple in number (almost 253)
Self-referencing tables
Referential Integrity
Indexing Foreign Key constraint
Delete and Update Rules

Implementing Foreign
Key by SSMS
Step1 - Open Table in design mode, right click on any column and choose Relationships
option.

Implementing Foreign
Key by SSMS
Step2 -

Foreign Key Delete & Update


Rules
No Action
Deletion or update fails with an error.
Cascade
All the rows with foreign keys pointing to deleted/updated row
are also deleted/updated.
Set Null
All the rows in foreign key table will be set to null value for FK
Column.
Set Default
All the rows in foreign key table will be set to default value for
FK column.

Check Constraint
Enforces domain integrity by limiting the values that can be
put in a column.
Evaluates to True/False/Unknown.
Multiple Check Constraint can be applied to a single column.
Check constraints performed only during Insert and Update
statements.

Implementing Check
Constraint by SSMS
Step1 - Open Table in design mode, right click on any column and choose Check
Constraints option.

Implementing Check
Constraint by SSMS
Step2 -

Default Constraint

Implementing Default Constraint by SSMS


Open Table in design mode, Select column for Default Constraint and Set Default
value under Colum Properties.

Implementing Constraints through


TSQL

Enable/Disable and Drop


Constraints through TSQL

List of Constraints applied on a


table

Potrebbero piacerti anche