Add Validated Constraints to a SQL Server Table

Constraints keep invalid values out of a table regardless of which application writes them. SQL Server uses ALTER COLUMN with the column's data type to change nullability, and ADD CONSTRAINT for named uniqueness and check rules.

Inspect Existing Values First

Before applying a required-value rule to a real table, count nulls. Before adding uniqueness, group by the proposed key and look for counts greater than one. Before adding a check, query rows that violate the proposed expression. Resolve those records through an agreed data correction rather than silently deleting them or disabling validation.

Rehearse with Disposable Data

In a fresh query session, run the following complete batch. The transaction rolls back both the demonstration table and its schema changes.

SQL
SET XACT_ABORT ON;
BEGIN TRY
    BEGIN TRANSACTION;

    CREATE TABLE #Products
    (
        ProductId int NOT NULL,
        Code nvarchar(20) NULL,
        Quantity int NULL
    );
    INSERT #Products (ProductId, Code, Quantity)
    VALUES (1, N'A100', 4), (2, N'B200', 0);

    ALTER TABLE #Products ALTER COLUMN Code nvarchar(20) NOT NULL;
    ALTER TABLE #Products ALTER COLUMN Quantity int NOT NULL;
    ALTER TABLE #Products ADD UNIQUE (Code);
    ALTER TABLE #Products WITH CHECK ADD CHECK (Quantity >= 0);

    SELECT ProductId, Code, Quantity
    FROM #Products
    ORDER BY ProductId;

    ROLLBACK TRANSACTION;
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
    THROW;
END CATCH;

The batch returns the two valid products, then removes its changes. Duplicate codes, negative quantities and null quantities would now violate the intended rules while the table exists. Anonymous constraints avoid shared temporary-object constraint-name collisions in this demonstration.

Name Production Rules Clearly

For an existing permanent table with valid data, the corresponding check syntax is:

SQL
-- Template: substitute the reviewed table and rule.
ALTER TABLE dbo.Products
WITH CHECK ADD CONSTRAINT CK_Products_Quantity
CHECK (Quantity >= 0);

WITH CHECK validates existing rows. Avoid using WITH NOCHECK merely to make deployment succeed. A check expression that evaluates to UNKNOWN for null input does not reject it, which is why a required quantity also needs NOT NULL.

SQL Server's single-column unique constraint permits only one null value. For a different null policy, investigate a deliberately designed filtered unique index. Schedule schema changes with their locking and validation cost in mind, and preserve the full intended data type when changing nullability.

Microsoft References

Author: Herman Schoenfeld