Getting Started:
Constraints are rules assigned to columns in your SQL tables. The main use of a Constraint is to help ensure that data integrity measures are met. Data integrity is very important. The whole idea of Data Integrity is to maintain a consistency of data. Constraints assist with Data Integrity, referential integrity(Primary Keys and Foreign Keys), and aids Normalization for your Database tables.
Data Integrity:
Lets say that we have a SQL table named “Contacts” and one of the columns in this table is “PhoneNumber”. Now when you think of storing a phone number, there’s many formats that come to mind:
- (xxx) xxx – xxxx
- xxx-xxx-xxxx
- xxxxxxxxxx
Data Integrity is ensuring that you pick a format for “Phone Numbers” and stick to that format. You would be violating Data Integrity if you chose to store format #1, #2 and #3 into the PhoneNumber column of the Contacts Table.
Types of Constraints:
On SQL Server, there are many types of Constraints that you can utilize. Below are the most commonly used:
- PRIMARY KEY
- FOREIGN KEY
- UNIQUE
- NOT NULL
- CHECK
Using “PRIMARY KEY” Constraint:
The Primary Key Constraint, enforces that a column value must be unique and specifies the column as the Primary Key.
Example of Creating a Primary key on a CREATE TABLE statement:
-----------------------------------------------
CREATE TABLE TableName
(
[ID] INT IDENTITY(1,1) PRIMARY KEY,
[Column1] NVARCHAR(200),
[Column2] NVARCHAR(200)
)
-----------------------------------------------
You can add a Primary Key Constraint to an existing table:
-----------------------------------------------
ALTER TABLE TableName
ADD CONSTRAINT Give_Constraint_a_Name PRIMARY KEY(ColumnName)
-----------------------------------------------
Using “FOREIGN KEY” Constraint:
The Foreign Key Constraint allows you to specify that a column in your table is the Primary key to another table, thus granting you linking access to the other table via the value in this column. This promotes referential integrity, meaning that you're making your SQL Table a dependent to another table(Child of Parent).
I’ve created a simple example, there are two tables “Table1” and “Table2”":
-----------------------------------------------
/*Parent Table */
CREATE TABLE Table1
(
[Table1ID] INT IDENTITY(1,1) PRIMARY KEY,
[Column1] NVARCHAR(200),
[Column2] NVARCHAR(200),
[Column3] NVARCHAR(200)
)
/*Dependent Table */
CREATE TABLE Table2
(
[Table2ID] INT IDENTITY(1,1) PRIMARY KEY,
[Table1ID] INT FOREIGN KEY REFERENCES Table1 (Table1ID),
[Column1] NVARCHAR(200),
[Column2] NVARCHAR(200),
[Column3] NVARCHAR(200)
)
-----------------------------------------------
NOTE: By adding a FOREIGN KEY constraint t