LESSON 6 OF 14

Constraints: Primary Keys, Foreign Keys, and Data Integrity

Learn to use PRIMARY KEY, FOREIGN KEY, NOT NULL, UNIQUE, CHECK, and DEFAULT constraints to build reliable SQL Server tables and one-to-many relationships.

45 dk 124

Introduction

Tables in a database are not merely passive containers of rows and columns. SQL Server uses constraints to control which values are accepted, which values must be unique, and how data in related tables remains connected. These rules provide an additional protection layer against errors in application code.

In this lesson, you will study PRIMARY KEY, FOREIGN KEY, NOT NULL, UNIQUE, CHECK, and DEFAULT constraints. You will also create a one-to-many relationship in which one department can have multiple employees, then test valid and invalid data operations.

Constraints do more than reject incorrect statements. They document the rules of the data model, improve the reliability of reports, and keep data consistent when it is accessed by different applications, scripts, or administrative tools.

1. What is data integrity?

Data integrity means that information in a database remains accurate, consistent, and compliant with defined rules. In relational database systems, three common categories are useful:

  • Entity integrity: Ensures that every row can be identified uniquely. It is commonly implemented with a PRIMARY KEY.
  • Referential integrity: Ensures that FOREIGN KEY values in one table exist in the related parent table.
  • Domain integrity: Restricts the values that can be stored in a column. NOT NULL, CHECK, UNIQUE, and DEFAULT constraints contribute to this goal.

Implementing a rule only in the application layer is risky. A web application may check that an email address is unique, but another application, a data-import script, or an administrator working in SSMS may access the same database. A UNIQUE constraint enforces the rule at the database level.

2. Using PRIMARY KEY to identify rows

A PRIMARY KEY is a column or group of columns that uniquely identifies each row in a table. A table can have only one primary key constraint, although that constraint may contain multiple columns. Primary key columns cannot contain NULL values and their values must be unique.

In many basic scenarios, the IDENTITY property is used so that SQL Server generates new identifier values:

CREATE TABLE dbo.Departments
(
    DepartmentID int IDENTITY(1,1) NOT NULL,
    DepartmentName nvarchar(100) NOT NULL,

    CONSTRAINT PK_Departments
        PRIMARY KEY (DepartmentID)
);

IDENTITY(1,1) specifies an initial value of 1 and an increment of 1. It does not guarantee that values will be gap-free. Deleted rows or failed operations can leave gaps, so an IDENTITY value should usually be treated as a technical key rather than a business document number.

3. NOT NULL and DEFAULT constraints

NOT NULL prevents a column from accepting NULL. If leaving an employee’s name unknown is not acceptable for the business, the column should be defined as NOT NULL. NULL is not the same as an empty string; it represents an unknown, missing, or inapplicable value.

A DEFAULT constraint specifies the value to use when an INSERT statement does not provide a value for that column. In the following table, the employee status becomes Active and the hiring date becomes the current date when those values are omitted:

CREATE TABLE dbo.Employees
(
    EmployeeID int IDENTITY(1,1) NOT NULL,
    DepartmentID int NOT NULL,
    FullName nvarchar(150) NOT NULL,
    Email nvarchar(255) NOT NULL,
    Salary decimal(12,2) NOT NULL,
    EmploymentStatus varchar(20) NOT NULL
        CONSTRAINT DF_Employees_EmploymentStatus DEFAULT ('Active'),
    HireDate date NOT NULL
        CONSTRAINT DF_Employees_HireDate DEFAULT (CONVERT(date, GETDATE())),

    CONSTRAINT PK_Employees
        PRIMARY KEY (EmployeeID)
);

A DEFAULT is applied when the column is omitted from the INSERT statement. If NULL is explicitly supplied, NULL is stored when the column permits it; otherwise, the operation fails because of NOT NULL. A DEFAULT also does not populate existing rows retroactively.

4. Creating alternative unique values with UNIQUE

The primary key is the main identity of a row. Other columns may also need to contain no duplicates. If department names or employee email addresses must be unique, use a UNIQUE constraint:

ALTER TABLE dbo.Departments
ADD CONSTRAINT UQ_Departments_DepartmentName
    UNIQUE (DepartmentName);

ALTER TABLE dbo.Employees
ADD CONSTRAINT UQ_Employees_Email
    UNIQUE (Email);

A UNIQUE constraint enforces uniqueness for columns that are not the primary key. SQL Server creates a unique index to enforce this rule. SQL Server UNIQUE columns can accept NULL, so the intended NULL behavior should be considered during design. If an email address is mandatory for every employee, combine UNIQUE with NOT NULL.

Several columns can also be unique as a combination. For example, if the same employee name should appear only once within a department, define a table-level constraint:

ALTER TABLE dbo.Employees
ADD CONSTRAINT UQ_Employees_Department_FullName
    UNIQUE (DepartmentID, FullName);

With this rule, DepartmentID and FullName do not need to be unique individually. The combination formed by both columns must be unique.

5. Restricting valid values with CHECK

A CHECK constraint requires a column or row to satisfy a logical condition. It can be used to ensure that a salary is greater than zero, an employment status belongs to an approved list, and a hire date is not in the future.

ALTER TABLE dbo.Employees
ADD CONSTRAINT CK_Employees_Salary_Positive
    CHECK (Salary > 0);

ALTER TABLE dbo.Employees
ADD CONSTRAINT CK_Employees_Status_Allowed
    CHECK (EmploymentStatus IN ('Active', 'OnLeave', 'Inactive'));

ALTER TABLE dbo.Employees
ADD CONSTRAINT CK_Employees_HireDate_NotFuture
    CHECK (HireDate <= CONVERT(date, GETDATE()));

A row is rejected when the CHECK expression evaluates to FALSE. NULL values require special attention. A CHECK expression can produce UNKNOWN, and UNKNOWN does not always behave like FALSE. For columns that must contain a value, using NOT NULL together with CHECK is safer.

6. Creating a one-to-many relationship with FOREIGN KEY

A FOREIGN KEY connects a column in one table to a primary key or suitable unique key in another table. In this example, Departments is the parent table and Employees is the child table. One department may have many employees, while each employee is assigned to one department.

ALTER TABLE dbo.Employees
ADD CONSTRAINT FK_Employees_Departments
    FOREIGN KEY (DepartmentID)
    REFERENCES dbo.Departments (DepartmentID);

After the relationship is created, Employees can contain only DepartmentID values that exist in Departments. Therefore, insert rows into the parent table first:

INSERT INTO dbo.Departments (DepartmentName)
VALUES (N'Information Technology'),
       (N'Human Resources');

INSERT INTO dbo.Employees
    (DepartmentID, FullName, Email, Salary)
VALUES
    (1, N'Aylin Demir', N'aylin.demir@example.com', 42000.00),
    (1, N'Mert Kaya', N'mert.kaya@example.com', 38500.00),
    (2, N'Selin Aras', N'selin.aras@example.com', 36000.00);

EmploymentStatus and HireDate are omitted from the second INSERT, so their DEFAULT values are used. The following statement fails because of the FOREIGN KEY constraint:

-- Fails if DepartmentID = 99 does not exist
INSERT INTO dbo.Employees
    (DepartmentID, FullName, Email, Salary)
VALUES
    (99, N'Invalid Record', N'invalid@example.com', 25000.00);

7. Referential integrity and delete behavior

With the default NO ACTION behavior, a parent row cannot be deleted while child rows refer to it. This prevents orphaned employee rows when the related department is removed.

-- Fails while related employees exist
DELETE FROM dbo.Departments
WHERE DepartmentID = 1;

If the business rule requires it, you can use ON DELETE CASCADE. In that case, deleting a department also deletes its related employees:

CREATE TABLE dbo.ProjectAssignments
(
    AssignmentID int IDENTITY(1,1) NOT NULL,
    EmployeeID int NOT NULL,
    ProjectName nvarchar(150) NOT NULL,

    CONSTRAINT PK_ProjectAssignments
        PRIMARY KEY (AssignmentID),
    CONSTRAINT FK_ProjectAssignments_Employees
        FOREIGN KEY (EmployeeID)
        REFERENCES dbo.Employees (EmployeeID)
        ON DELETE CASCADE
);

CASCADE is powerful and must be selected carefully. It can cause large amounts of related data to be deleted unexpectedly. In systems that must preserve history or audit records, NO ACTION is often preferred, with a status change used instead of physical deletion. If SET NULL is used, the foreign key column must allow NULL.

8. Inspecting and modifying constraints

In SSMS Object Explorer, you can right-click a table and inspect its Keys or Constraints folders. You can also query system catalog views with T-SQL:

SELECT
    kc.name AS ConstraintName,
    kc.type_desc AS ConstraintType,
    OBJECT_SCHEMA_NAME(kc.parent_object_id) AS SchemaName,
    OBJECT_NAME(kc.parent_object_id) AS TableName
FROM sys.key_constraints AS kc
WHERE kc.parent_object_id = OBJECT_ID(N'dbo.Employees');

To remove a constraint, specify its name explicitly:

ALTER TABLE dbo.Employees
DROP CONSTRAINT CK_Employees_Salary_Positive;

Before removing a constraint in a production database, evaluate its effects on application behavior, reports, and data-import processes. When a FOREIGN KEY or CHECK constraint is added to an existing table, SQL Server checks existing rows as well. Existing violations can cause the ALTER TABLE operation to fail.

9. Common mistakes

  • Inserting into the child table first: Create the referenced primary key row in the parent table before inserting the foreign key value.
  • Confusing primary keys and unique fields: A primary key is the main row identifier; UNIQUE is an additional uniqueness rule.
  • Using only CHECK for a required column: Use NOT NULL as well when NULL must be prohibited.
  • Using CASCADE without analysis: A delete can propagate through several related tables and may be difficult to reverse.
  • Leaving constraints unnamed: Names such as PK_Employees and FK_Employees_Departments make maintenance easier.
  • Relying only on application validation: Important integrity rules should also be enforced by the database.

10. Short practice exercise

Create dbo.Categories and dbo.Products tables. Categories should contain an identifier and a unique category name. Products should contain a category foreign key, a required product name, a CHECK constraint requiring a price greater than zero, a unique SKU, and a default stock status.

  1. Insert at least two categories.
  2. Insert two valid products.
  3. Try to insert a product with a CategoryID that does not exist.
  4. Insert a second product with the same SKU to test UNIQUE.
  5. Use a negative price to test CHECK.
  6. Insert a product without specifying the stock status and observe the DEFAULT value.

Conclusion

In this lesson, you learned how to protect data integrity at the SQL Server database level. PRIMARY KEY defines row identity, FOREIGN KEY enforces table relationships, NOT NULL makes a value mandatory, UNIQUE prevents duplicates, CHECK limits acceptable values, and DEFAULT supplies values when they are omitted.

When designing related tables, identify the business rules first and then implement those rules with clear, named constraints wherever possible. The SELECT, JOIN, and aggregate queries in later lessons will then operate on data that is more consistent and trustworthy.

Sources