what is database constraints?

Asked 23 days ago
Updated 20 days ago
Viewed 78 times

1 Answer


0

Database constraints are rules applied to database tables to make sure the data stored is accurate, consistent, and reliable.

Think of them as guardrails for your data — they prevent invalid or unwanted data from getting into the database.

Why database constraints are needed

They help to:

  • Prevent duplicate or invalid data
  • Maintain data integrity
  • Enforce relationships between tables
  • Reduce bugs caused by bad data

Common types of database constraints

1. PRIMARY KEY

  • Uniquely identifies each row in a table
  • Cannot be NULL
  • No duplicate values

Example:

UserId INT PRIMARY KEY

2. FOREIGN KEY

  • Creates a relationship between two tables
  • Ensures values exist in the referenced table

Example:

UserId INT,
FOREIGN KEY (UserId) REFERENCES Users(UserId)

3. UNIQUE

  • Ensures all values in a column are unique
  • Allows only one NULL (depends on DB)

Example:

Email VARCHAR(100) UNIQUE

4. NOT NULL

  • Prevents NULL values in a column

Example:

Name VARCHAR(50) NOT NULL

5. CHECK

  • Validates data using a condition

Example:

Age INT CHECK (Age >= 18)

6. DEFAULT

  • Assigns a default value if none is provided

Example:

CreatedDate DATETIME DEFAULT GETDATE()

Simple real-world example

CREATE TABLE Users (
    UserId INT PRIMARY KEY,
    Email VARCHAR(100) UNIQUE NOT NULL,
    Age INT CHECK (Age >= 18),
    CreatedDate DATETIME DEFAULT GETDATE()
);

Here:

  • UserId must be unique
  • Email cannot be duplicated or empty
  • Age must be 18 or above
  • CreatedDate auto-fills if not provided

In one line:

Database constraints enforce rules to keep your data correct and trustworthy.

answered 20 days ago by Anubhav Kumar

Your Answer