SQL Server Interview Question #19
What is a constraint in SQL Server?
SQL Server Fundamentals Junior Beginner
Detailed Explanation
A constraint is a rule enforced by SQL Server to protect data validity and integrity. Common constraints include PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK, and DEFAULT.
Database constraints are important even when an ASP.NET Core application performs model validation, because constraints provide an integrity boundary at the database level for every application or process that writes data.
Code Example
CREATE TABLE Products
(
Id INT IDENTITY(1,1) PRIMARY KEY,
Name NVARCHAR(200) NOT NULL,
SKU NVARCHAR(50) UNIQUE,
Price DECIMAL(18,2) NOT NULL,
IsActive BIT NOT NULL
CONSTRAINT DF_Products_IsActive DEFAULT 1,
CONSTRAINT CK_Products_Price CHECK (Price >= 0)
);