Check Constraint Wizard (SQL Server)

From RapidSQL

Go Up to Microsoft SQL Server Object Wizards

Check Constraints with With CHECK and With NOCHECK tells SQL Server whether to check the rows before adding or enabling the constraint. For more information about this feature, see Check Constraint Wizard (SQL Server).

To create a new check constraint using a wizard:

  1. Open a creation wizard for a check constraint. For details, see Opening an Object Wizard.
  2. Use the following topic as a guide to performing tasks as you pass through the wizard panels:
  3. Finally, use the Execute button to create the object.

Check Constraint (SQL Server) - Definition

When creating or editing a check constraint, this tab/panel lets you work with the following settings:

Setting Description

Table Schema and Table Name

Identify the table for which the constraint is being created.

Name

Lets you type the name of the constraint.

Enabled

If selected, enables the check constraint.

With CHECK

SQL Server validates all existing rows in the table against the new constraint before enabling it. If any existing row violates the constraint, the constraint is not enabled (or is added but flagged as not trusted, depending on server version and syntax used).

With NOCHECK

SQL Server adds or enables the constraint without validating existing rows against it. Only rows inserted or updated after the constraint is enabled are checked. Existing data that violates the constraint is left in place.

The Table Schema, Table Name, and Name fields on the same Definition panel identify and name the constraint being created. Enabled turns the constraint on or off. The With CHECK/With NOCHECK setting only governs how existing data is treated at the moment the constraint is added or re-enabled — it does not change how the constraint behaves for new data going forward.

Notes

Use WITH NOCHECK when you know existing data has values that would fail the new constraint and you don't want (or aren't able to) clean it up before adding the constraint — for example, during a migration where cleanup will happen later.

A constraint added with WITH NOCHECK still applies going forward: SQL Server enforces it on every subsequent insert or update, it simply doesn't retroactively validate what's already there.

If you need the constraint to guarantee all data (old and new) is valid, use WITH CHECK and resolve any validation failures on existing rows first.