SQL Server Data Integrity: Preventing Invalid Rows with CHECK, UNIQUE, and FOREIGN KEY

SQL Server Data Integrity: Preventing Invalid Rows with CHECK, UNIQUE, and FOREIGN KEY

Application-level validation is useful, but the database is the final protection layer when multiple services, ETL jobs, or direct SQL clients can write to the same tables. Rules such as “an email address must be unique” or “a delivery date cannot precede the order date” should not exist only in application code.

This article builds a small order system using three constraint types: UNIQUE prevents duplicates, CHECK rejects invalid values, and FOREIGN KEY prevents orders from referencing a customer that does not exist. The goal is to solve a realistic data-quality problem rather than list isolated syntax examples.

The problem: corrupted data during order imports

Assume that customers and orders are loaded by separate application paths. A daily CSV import produces several defects:

  • The same email address creates multiple customer rows.
  • An order total is negative or accidentally recorded as zero.
  • A delivery date is earlier than the order date.
  • An order references a customer ID that is not present.

Even if the application checks these conditions, two concurrent requests can both decide that a customer does not exist. Database constraints provide the final guarantee and prevent invalid data from becoming durable.

Creating the schema with constraints

CREATE SCHEMA Sales;
GO

CREATE TABLE Sales.Customer
(
    CustomerId  int IDENTITY(1,1) NOT NULL,
    Email       nvarchar(320) NOT NULL,
    DisplayName nvarchar(150) NOT NULL,
    IsActive    bit NOT NULL CONSTRAINT DF_Customer_IsActive DEFAULT (1),
    CONSTRAINT PK_Customer PRIMARY KEY CLUSTERED (CustomerId),
    CONSTRAINT UQ_Customer_Email UNIQUE (Email),
    CONSTRAINT CK_Customer_DisplayName CHECK (LEN(LTRIM(RTRIM(DisplayName))) > 0)
);

CREATE TABLE Sales.OrderHeader
(
    OrderId      bigint IDENTITY(1,1) NOT NULL,
    CustomerId   int NOT NULL,
    OrderDate    datetime2(0) NOT NULL,
    DeliveryDate datetime2(0) NULL,
    TotalAmount  decimal(12,2) NOT NULL,
    Status       varchar(20) NOT NULL,
    CONSTRAINT PK_OrderHeader PRIMARY KEY CLUSTERED (OrderId),
    CONSTRAINT FK_OrderHeader_Customer
        FOREIGN KEY (CustomerId) REFERENCES Sales.Customer(CustomerId),
    CONSTRAINT CK_OrderHeader_Dates
        CHECK (DeliveryDate IS NULL OR DeliveryDate >= OrderDate),
    CONSTRAINT CK_OrderHeader_TotalAmount
        CHECK (TotalAmount > 0),
    CONSTRAINT CK_OrderHeader_Status
        CHECK (Status IN ('Pending', 'Paid', 'Shipped', 'Cancelled'))
);

CREATE INDEX IX_OrderHeader_CustomerId
    ON Sales.OrderHeader(CustomerId);

A UNIQUE constraint expresses a business rule for a column or column combination that is not the primary key. The technical identity of a customer is CustomerId; the business rule that an email cannot be reused is represented separately by UQ_Customer_Email.

A CHECK constraint limits values with a logical expression evaluated for the row. It cannot query another table, so it is not the right mechanism for verifying that a customer exists. That cross-table rule belongs to the FOREIGN KEY.

Testing rejected rows

The following statements insert valid data:

INSERT INTO Sales.Customer (Email, DisplayName)
VALUES (N'ayse@example.com', N'Ayşe Demir');

INSERT INTO Sales.OrderHeader
    (CustomerId, OrderDate, DeliveryDate, TotalAmount, Status)
VALUES
    (1, '2026-04-10', '2026-04-12', 249.90, 'Paid');

Inserting the same email again violates the UNIQUE constraint:

INSERT INTO Sales.Customer (Email, DisplayName)
VALUES (N'ayse@example.com', N'Another Name');

A negative amount or an invalid date sequence is rejected by CHECK constraints:

INSERT INTO Sales.OrderHeader
    (CustomerId, OrderDate, DeliveryDate, TotalAmount, Status)
VALUES
    (1, '2026-04-10', '2026-04-09', -10.00, 'Paid');

A nonexistent customer ID produces a FOREIGN KEY violation:

INSERT INTO Sales.OrderHeader
    (CustomerId, OrderDate, TotalAmount, Status)
VALUES
    (999999, SYSdatetime(), 50.00, 'Pending');

The application should catch these errors and return a useful message, but catching an error is not a reason to remove the constraint. The database protects the data; the application protects the user experience.

UNIQUE constraint or unique index?

Both mechanisms enforce uniqueness through an index internally. A UNIQUE constraint is usually clearer when the rule represents business meaning, such as “an email address may belong to only one customer.” A unique index is often more appropriate when the index is primarily an access-path or specialized indexing decision.

Do not assume that nullable columns behave like ordinary optional values. In SQL Server, a UNIQUE constraint on a nullable single column permits at most one NULL value. If the desired rule is “empty email is allowed, but every non-empty email must be unique,” model and test that requirement deliberately instead of relying on an assumption.

Why index the FOREIGN KEY column?

A FOREIGN KEY does not automatically create an index. However, OrderHeader.CustomerId is commonly used in joins, customer-order lookups, and checks performed when a parent row is changed or deleted. That is why the example creates IX_OrderHeader_CustomerId explicitly.

The index can reduce the work required for queries such as “how many orders belong to this customer?” and can help SQL Server locate dependent rows more efficiently. It is not automatically beneficial in every workload, so validate the design with execution plans, row counts, and write-performance measurements.

Decide carefully before using ON DELETE CASCADE

The default referential action is NO ACTION. Therefore, deleting a customer that still has orders fails instead of silently removing historical data. For most order and financial systems, this is the safer default.

ON DELETE CASCADE is suitable only when child rows have no independent business value and must disappear with the parent. Temporary sessions, disposable shopping carts, or ownership records may fit this model. Historical orders usually do not; a soft-delete approach such as setting IsActive = 0 is often safer than physically deleting the customer.

Adding constraints to an existing dirty table

Adding a constraint to a populated production table can fail immediately. First measure the violations:

SELECT Email, COUNT(*) AS DuplicateCount
FROM Sales.Customer
GROUP BY Email
HAVING COUNT(*) > 1;

SELECT *
FROM Sales.OrderHeader
WHERE TotalAmount <= 0
   OR (DeliveryDate IS NOT NULL AND DeliveryDate < OrderDate);

SELECT o.*
FROM Sales.OrderHeader AS o
LEFT JOIN Sales.Customer AS c
    ON c.CustomerId = o.CustomerId
WHERE c.CustomerId IS NULL;

Next, define a remediation policy: merge duplicate customers, move orphaned orders to a quarantine table, or resolve invalid dates with the business owner. Using WITH NOCHECK may appear to make deployment easier, but it can leave an untrusted relationship behind. That weakens confidence in the schema and should not replace proper cleanup and validation.

Production checklist

  • Protect business keys that must not repeat with UNIQUE constraints.
  • Use CHECK constraints for ranges, statuses, and same-row date rules.
  • Use FOREIGN KEY constraints for relationships between tables.
  • Evaluate indexes on FOREIGN KEY columns according to join and delete patterns.
  • Choose CASCADE according to the data lifecycle; NO ACTION is safer for most critical history.
  • Report existing violations and test the cleanup plan before adding constraints in production.

Well-designed constraints are usually cheaper than repairing corrupted data later. Application validation can provide fast feedback, while CHECK, UNIQUE, and FOREIGN KEY constraints preserve integrity across every write path.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published