Paramclasses Academy - Blog

Tutorials Details

←
Post 22 of 40
→

SQL Server Constraints Explained: NOT NULL, UNIQUE, CHECK and DEFAULT with Examples

SQL Server Constraints Explained: NOT NULL, UNIQUE, CHECK and DEFAULT with Examples

November 18, 2026

✨ SQL Server Constraints: NOT NULL, UNIQUE, CHECK and DEFAULT

???? Introduction

When working with Microsoft SQL Server, maintaining accurate, consistent, and reliable data is one of the most important responsibilities of a database developer.

Imagine that you are developing a Student Management System for a college. The system stores student names, email addresses, ages, phone numbers, and registration dates.

Now consider these situations:

  • A student registers without entering a name.

  • Two students register using the same email address.

  • A student enters a negative age.

  • A registration record is created without specifying its registration date.

These situations can create incorrect or inconsistent database records.

How can we prevent such problems directly at the database level?

The answer is SQL Server Constraints.

Constraints are rules applied to database columns or tables to control which values can be stored. They help maintain data integrity by rejecting data that violates the defined rules.

In this tutorial by Param Classes, we will learn four important SQL Server constraints:

  1. NOT NULL Constraint – Prevents NULL values.

  2. UNIQUE Constraint – Prevents duplicate values.

  3. CHECK Constraint – Validates values against specific conditions.

  4. DEFAULT Constraint – Automatically supplies a predefined value when no value is provided.

Let's understand each constraint with practical SQL queries and real-world examples.


???? 1. What Are Constraints in SQL Server?

A Constraint is a rule defined on a database table or column to control the type of data that can be inserted or updated.

SQL Server checks these rules whenever data is inserted or modified.

If the supplied data violates an enforced constraint, SQL Server rejects the operation.

⭐ Why Do We Use Constraints?

Constraints are used to:

  • Maintain data accuracy and consistency.

  • Prevent invalid data from entering tables.

  • Avoid duplicate values.

  • Ensure required fields contain values.

  • Apply business rules to database records.

  • Improve database reliability.

  • Maintain data integrity across applications.

???? Common SQL Server Constraints

Constraint Purpose
NOT NULL Prevents NULL values
UNIQUE Prevents duplicate values
CHECK Validates data using conditions
DEFAULT Provides a predefined value
PRIMARY KEY Uniquely identifies each record
FOREIGN KEY Maintains relationships between tables

In this tutorial, our main focus will be NOT NULL, UNIQUE, CHECK, and DEFAULT constraints.


???? 2. NOT NULL Constraint in SQL Server

???? What Is a NOT NULL Constraint?

The NOT NULL Constraint ensures that a particular column cannot contain NULL values.

It is used when a field must always have a value.

For example, in a Student Management System, the student name and email address may be mandatory fields.

A student should not be registered without providing these required details.

⭐ Syntax

CREATE TABLE table_name
(
    column_name datatype NOT NULL
);

????‍???? Practical Example: Create a Students Table

CREATE TABLE Students
(
    StudentID INT PRIMARY KEY,
    StudentName VARCHAR(100) NOT NULL,
    Email VARCHAR(100) NOT NULL,
    Age INT
);

???? Explanation

  • StudentID: Stores the unique student ID.

  • StudentName: Cannot contain NULL values.

  • Email: Cannot contain NULL values.

  • Age: Can contain NULL because NOT NULL is not specified.

???? Insert Valid Records

INSERT INTO Students
(StudentID, StudentName, Email, Age)
VALUES
(101, 'Rahul Sharma', 'rahul@gmail.com', 21),
(102, 'Priya Verma', 'priya@gmail.com', 22),
(103, 'Amit Kumar', 'amit@gmail.com', 20);

These records will be inserted successfully because the required columns contain values.

❌ Example of an Invalid Record

INSERT INTO Students
(StudentID, StudentName, Email, Age)
VALUES
(104, NULL, 'rohit@gmail.com', 23);

Expected Result: SQL Server generates an error because StudentName does not allow NULL values.

⭐ Important Points

  • NOT NULL prevents NULL values.

  • It does not prevent duplicate values.

  • It is useful for mandatory database fields.

  • It can be specified when creating a table or added to an existing column after checking the existing data.


???? 3. UNIQUE Constraint in SQL Server

???? What Is a UNIQUE Constraint?

The UNIQUE Constraint ensures that values in a specified column or combination of columns remain unique.

It prevents duplicate entries in a column where repeated values are not allowed.

For example, in a student database, every student should have a different email address.

If two students try to register using the same email address, SQL Server should reject the duplicate entry.

⭐ Syntax

CREATE TABLE table_name
(
    column_name datatype UNIQUE
);

????‍???? Practical Example: Create a Students Table with UNIQUE

CREATE TABLE StudentDetails
(
    StudentID INT PRIMARY KEY,
    StudentName VARCHAR(100) NOT NULL,
    Email VARCHAR(100) UNIQUE,
    PhoneNumber VARCHAR(15) UNIQUE
);

???? Explanation

  • StudentID: Uniquely identifies each student.

  • StudentName: Stores the student's name.

  • Email: Does not allow duplicate non-NULL values.

  • PhoneNumber: Does not allow duplicate non-NULL values.

???? Insert Valid Records

INSERT INTO StudentDetails
(StudentID, StudentName, Email, PhoneNumber)
VALUES
(1, 'Rahul Sharma', 'rahul@gmail.com', '9876543210'),
(2, 'Priya Verma', 'priya@gmail.com', '9876543211'),
(3, 'Amit Kumar', 'amit@gmail.com', '9876543212');

These records will be inserted successfully because all email addresses and phone numbers are different.

❌ Example of Duplicate Email

INSERT INTO StudentDetails
(StudentID, StudentName, Email, PhoneNumber)
VALUES
(4, 'Neha Patel', 'rahul@gmail.com', '9876543213');

Expected Result: SQL Server generates a UNIQUE constraint violation because rahul@gmail.com already exists.

⭐ Important Points

  • UNIQUE prevents duplicate values.

  • A table can have multiple UNIQUE constraints.

  • A UNIQUE constraint can contain multiple columns.

  • Unlike a Primary Key, a UNIQUE constraint can allow NULL.

  • In SQL Server, a single-column UNIQUE constraint allows at most one NULL value.

Remember: PRIMARY KEY and UNIQUE both enforce uniqueness, but a table can have only one Primary Key constraint and multiple UNIQUE constraints.


???? 4. CHECK Constraint in SQL Server

???? What Is a CHECK Constraint?

The CHECK Constraint is used to validate data according to a specified condition.

It allows SQL Server to accept only those values that satisfy the defined condition.

For example:

  • A student's age must be at least 18.

  • An employee's salary must be greater than zero.

  • A product price cannot be negative.

  • A student's status must be one of the permitted values.

These rules can be implemented using CHECK constraints.

⭐ Syntax

CREATE TABLE table_name
(
    column_name datatype CHECK (condition)
);

????‍???? Practical Example: Create an Employees Table

CREATE TABLE Employees
(
    EmployeeID INT PRIMARY KEY,
    EmployeeName VARCHAR(100) NOT NULL,
    Age INT CHECK (Age >= 18),
    Salary DECIMAL(10,2) CHECK (Salary > 0)
);

???? Explanation

  • EmployeeID: Unique employee identification number.

  • EmployeeName: Employee name cannot be NULL.

  • Age: Must be 18 or greater.

  • Salary: Must be greater than zero.

???? Insert Valid Records

INSERT INTO Employees
(EmployeeID, EmployeeName, Age, Salary)
VALUES
(101, 'Rahul Sharma', 25, 25000),
(102, 'Priya Verma', 28, 35000),
(103, 'Amit Kumar', 30, 40000);

These records will be inserted successfully because they satisfy both CHECK conditions.

❌ Example of an Invalid Age

INSERT INTO Employees
(EmployeeID, EmployeeName, Age, Salary)
VALUES
(104, 'Rohit Singh', 16, 20000);

Expected Result: SQL Server generates a CHECK constraint violation because the employee's age is below 18.

❌ Example of an Invalid Salary

INSERT INTO Employees
(EmployeeID, EmployeeName, Age, Salary)
VALUES
(105, 'Neha Patel', 25, -5000);

Expected Result: SQL Server rejects the record because the salary must be greater than zero.

⭐ CHECK Constraint with IN Operator

You can also use the IN operator to restrict a column to specific values.

CREATE TABLE EmployeeStatus
(
    EmployeeID INT PRIMARY KEY,
    EmployeeName VARCHAR(100),
    Status VARCHAR(20),

    CONSTRAINT CK_EmployeeStatus
    CHECK (Status IN ('Active', 'Inactive', 'On Leave'))
);

In this example, the Status column accepts only:

  • Active

  • Inactive

  • On Leave

Any other non-NULL value will violate the CHECK constraint.

Important: CHECK constraints reject conditions that evaluate to FALSE. If NULL values must also be prohibited, combine CHECK with NOT NULL.


???? 5. DEFAULT Constraint in SQL Server

???? What Is a DEFAULT Constraint?

The DEFAULT Constraint automatically provides a predefined value when a column is not supplied in an INSERT statement or when the DEFAULT keyword is used.

It is useful when a particular column should receive a standard value if the user does not provide one.

For example, when a new employee joins a company, the employee status can automatically be set to Active.

Similarly, a registration date can automatically be assigned the current date.

⭐ Syntax

CREATE TABLE table_name
(
    column_name datatype DEFAULT default_value
);

????‍???? Practical Example: Create an Employee Table

CREATE TABLE EmployeeRecords
(
    EmployeeID INT PRIMARY KEY,
    EmployeeName VARCHAR(100) NOT NULL,
    City VARCHAR(50) DEFAULT 'Raipur',
    Status VARCHAR(20) DEFAULT 'Active',
    JoiningDate DATE DEFAULT (GETDATE())
);

???? Explanation

  • EmployeeID: Stores employee identification number.

  • EmployeeName: Stores employee name.

  • City: Automatically receives Raipur if omitted.

  • Status: Automatically receives Active if omitted.

  • JoiningDate: Automatically receives the current date if omitted.

???? Insert Records Without Default Columns

INSERT INTO EmployeeRecords
(EmployeeID, EmployeeName)
VALUES
(101, 'Rahul Sharma'),
(102, 'Priya Verma');

SQL Server automatically supplies the default values for City, Status, and JoiningDate.

???? Expected Output

EmployeeID EmployeeName City Status
101 Rahul Sharma Raipur Active
102 Priya Verma Raipur Active

JoiningDate will contain the current database server date at insertion time.

???? Insert a Record with Custom Values

INSERT INTO EmployeeRecords
(EmployeeID, EmployeeName, City, Status)
VALUES
(103, 'Amit Kumar', 'Bilaspur', 'Inactive');

In this example, the provided City and Status values are used instead of their default values. JoiningDate still receives its default value.

⭐ Important Points

  • DEFAULT provides a predefined value.

  • It works when the column is omitted or DEFAULT is specified.

  • An explicitly supplied NULL is not replaced by the DEFAULT value.

  • DEFAULT can use expressions such as GETDATE().

  • It helps reduce repetitive data entry.


???? 6. Difference Between NOT NULL, UNIQUE, CHECK and DEFAULT

All four constraints help maintain database integrity, but each performs a different function.

Constraint Main Purpose Example
NOT NULL Prevents NULL values StudentName cannot be NULL
UNIQUE Prevents duplicate values Email must be unique
CHECK Validates conditions Age must be 18 or above
DEFAULT Supplies a predefined value City defaults to Raipur

???? Quick Example

Consider an employee database:

  • NOT NULL: EmployeeName must be provided.

  • UNIQUE: EmployeeEmail must be different for each employee.

  • CHECK: Salary must be greater than zero.

  • DEFAULT: EmployeeStatus is Active if omitted.

Using these constraints together makes the database more reliable.


???? 7. How to Add Constraints to an Existing Table

You do not always need to define constraints when creating a new table.

SQL Server also allows you to add constraints to an existing table using the ALTER TABLE command.

A. Add a UNIQUE Constraint

ALTER TABLE Employees
ADD CONSTRAINT UQ_Employees_Email
UNIQUE (Email);

B. Add a CHECK Constraint

ALTER TABLE Employees
ADD CONSTRAINT CK_Employees_Age
CHECK (Age >= 18);

C. Add a DEFAULT Constraint

ALTER TABLE Employees
ADD CONSTRAINT DF_Employees_City
DEFAULT 'Raipur' FOR City;

D. Add a NOT NULL Constraint

ALTER TABLE Employees
ALTER COLUMN EmployeeName VARCHAR(100) NOT NULL;

Important: Before adding constraints to existing tables, check whether the current data satisfies the new rules. Otherwise, SQL Server may reject the operation.


???? 8. How to View Constraints in SQL Server

SQL Server provides system catalog views to inspect constraints defined on database tables.

Query 1: View All Constraints

SELECT
    name AS ConstraintName,
    type_desc AS ConstraintType
FROM sys.objects
WHERE type IN ('C', 'D', 'F', 'PK', 'UQ');

Query 2: View CHECK Constraints

SELECT
    name AS ConstraintName,
    definition
FROM sys.check_constraints;

Query 3: View DEFAULT Constraints

SELECT
    name AS ConstraintName,
    definition
FROM sys.default_constraints;

These queries help developers inspect the constraints defined in the current database.


???? 9. How to Delete a Constraint in SQL Server

Sometimes, a database developer needs to remove an existing constraint.

SQL Server provides the ALTER TABLE DROP CONSTRAINT command.

Syntax

ALTER TABLE table_name
DROP CONSTRAINT constraint_name;

Practical Example

ALTER TABLE Employees
DROP CONSTRAINT CK_Employees_Age;

This query removes the specified CHECK constraint from the Employees table.

Important: Removing a constraint also removes the protection provided by that rule. Always verify the requirement before dropping it.


???? 10. Real-World Applications of SQL Server Constraints

Constraints are used in almost every database-driven application.

???? A. Student Management System

  • StudentName: NOT NULL

  • Email: UNIQUE

  • Age: CHECK (Age >= 18)

  • RegistrationDate: DEFAULT (GETDATE())

???? B. E-Commerce Website

  • ProductName: NOT NULL

  • ProductCode: UNIQUE

  • ProductPrice: CHECK (ProductPrice > 0)

  • ProductStatus: DEFAULT ('Available')

???? C. Hospital Management System

  • PatientName: NOT NULL

  • PatientEmail: UNIQUE

  • PatientAge: CHECK (PatientAge >= 0)

  • RegistrationDate: DEFAULT (GETDATE())

???? D. Employee Management System

  • EmployeeName: NOT NULL

  • EmployeeEmail: UNIQUE

  • Salary: CHECK (Salary > 0)

  • EmployeeStatus: DEFAULT ('Active')

These examples demonstrate how constraints help businesses maintain accurate and consistent database records.


???? 11. Common Beginner Mistakes in SQL Server Constraints

While learning constraints, beginners may encounter the following problems.

1. Confusing NULL with Zero

NULL means a missing or unknown value. Zero is an actual numeric value.

2. Using UNIQUE Instead of PRIMARY KEY

UNIQUE prevents duplicates, whereas a Primary Key uniquely identifies every record and does not allow NULL.

3. Forgetting CHECK Conditions

Incorrect conditions may reject valid records or allow unintended values.

4. Expecting DEFAULT to Replace NULL

DEFAULT is not automatically applied when an explicit NULL is supplied.

5. Adding Constraints Without Checking Existing Data

Existing duplicate or invalid values may prevent a new constraint from being added.

6. Using Unclear Constraint Names

Meaningful names such as CK_Employees_Age and DF_Employees_City make database maintenance easier.


???? 12. Frequently Asked Questions (FAQs)

Q1. What are constraints in SQL Server?

Constraints are rules applied to database columns or tables to maintain data accuracy, consistency, and integrity.

Q2. What is the purpose of the NOT NULL constraint?

NOT NULL prevents a column from accepting NULL values. It is useful for mandatory fields such as names and required identification details.

Q3. What is the difference between UNIQUE and PRIMARY KEY?

Both enforce uniqueness. However, a table can have only one Primary Key constraint, while it can have multiple UNIQUE constraints. A Primary Key cannot contain NULL values.

Q4. What is a CHECK constraint?

CHECK validates data against a specified condition, such as ensuring that age is at least 18 or salary is greater than zero.

Q5. What is a DEFAULT constraint?

DEFAULT automatically supplies a predefined value when a column is omitted from an INSERT statement or DEFAULT is specified.

Q6. Can we use multiple constraints on one column?

Yes. SQL Server allows multiple applicable constraints on a column, such as NOT NULL and CHECK.

Q7. Can we add constraints to an existing table?

Yes. We can use ALTER TABLE to add constraints to an existing table.

Q8. Can we remove a constraint in SQL Server?

Yes. Use ALTER TABLE with DROP CONSTRAINT followed by the constraint name.

Q9. Does DEFAULT insert a value when NULL is supplied?

No. If you explicitly insert NULL, SQL Server uses NULL when the column permits it. DEFAULT applies when the column is omitted or DEFAULT is specified.

Q10. Why are constraints important in database development?

Constraints help prevent invalid records, reduce data errors, enforce business rules, and maintain database reliability.


???? Conclusion

SQL Server Constraints play an important role in maintaining the accuracy, consistency, and reliability of relational databases.

In this tutorial, we learned four important constraints: NOT NULL, UNIQUE, CHECK, and DEFAULT with practical SQL Server examples.

We understood how NOT NULL prevents missing values, UNIQUE prevents duplicate entries, CHECK validates data using conditions, and DEFAULT automatically supplies predefined values.

We also explored how to add, view, and remove constraints using SQL Server commands and how these constraints are used in real-world applications such as Student Management Systems, E-Commerce Websites, Hospital Management Systems, and Employee Management Systems.

At Param Classes, our goal is to make SQL Server and database development easy to understand through practical examples, step-by-step tutorials, and real-world projects.

Keep practising these SQL queries in SQL Server Management Studio (SSMS) to strengthen your database development skills.

✨ Keep Learning | Keep Practising | Keep Growing with Param Classes!

←
Post 22 of 40
→