Tables and integrity
UNIQUE, CHECK, NOT NULL, and DEFAULT constraints
Constrain disposable rows and supply a default for an omitted value.
Lesson 53 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Intermediate
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Constrain disposable rows and supply a default for an omitted value. Run changing examples only on a disposable training instance. The example uses a session-local object or rolls back its changes.
Run the example
CREATE TABLE #Rules (RuleID int NOT NULL PRIMARY KEY,
Code nvarchar(20) NOT NULL UNIQUE, Quantity int NOT NULL CHECK (Quantity > 0),
IsActive bit NOT NULL DEFAULT (1));
INSERT INTO #Rules (RuleID, Code, Quantity) VALUES (1, N'A', 2);
SELECT RuleID, Code, Quantity, IsActive FROM #Rules;
DROP TABLE #Rules;Read it step by step
- NOT NULL rejects missing required values; UNIQUE prevents duplicate Code values.
- CHECK requires a positive Quantity for non-NULL inputs, and NOT NULL closes the NULL loophole.
- Because INSERT omits IsActive, DEFAULT supplies 1.
Check the result
| RuleID | Code | Quantity | IsActive |
|---|---|---|---|
| 1 | A | 2 | 1 |
No canonical table or constraint changes.
Practice
Create a temp table with a positive Price, unique Code, and default bit flag; insert one valid row without the flag.
Check your answer and expected result
Reveal answer
CREATE TABLE #Rules (Code nvarchar(20) NOT NULL UNIQUE,
Price decimal(10,2) NOT NULL CHECK (Price > 0),
IsActive bit NOT NULL DEFAULT (1));
INSERT INTO #Rules (Code, Price) VALUES (N'P', 12.50);
SELECT Code, Price, IsActive FROM #Rules;
DROP TABLE #Rules;| Code | Price | IsActive |
|---|---|---|
| P | 12.50 | 1 |
The omitted bit receives 1; the positive price satisfies CHECK.
Your progress
Reveal the check answer or reach the end to complete this lesson.