#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
Step 15
6 min read

Data Integrity Constraints

Learn how constraints keep your data clean and accurate.

What are Data Integrity Constraints?

All Constraints Summary
ConstraintPurposeExample
PRIMARY KEYUnique identifieruser_id
FOREIGN KEYLink tablescustomer_id references customers
UNIQUENo duplicatesemail, username
NOT NULLRequired fieldname, email
CHECKValidate valuesage >= 18, price > 0
5 rows

Constraints are rules that keep your data correct and reliable. They prevent bad data from entering your database.

Simple analogy: Like spell-check and grammar-check for your database - catches mistakes before they happen.

All Constraints Together

All Constraints Summary
ConstraintPurposeExample
PRIMARY KEYUnique identifieruser_id
FOREIGN KEYLink tablescustomer_id references customers
UNIQUENo duplicatesemail, username
NOT NULLRequired fieldname, email
CHECKValidate valuesage >= 18, price > 0
5 rows
CREATE TABLE users ( user_id SERIAL PRIMARY KEY, username VARCHAR(50) UNIQUE NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, age INTEGER CHECK (age >= 18), account_balance DECIMAL(10, 2) CHECK (account_balance >= 0) );

What each constraint does:

  • PRIMARY KEY: Unique identifier (no duplicates, not empty)
  • UNIQUE: No two users can have same username or email
  • NOT NULL: Username and email are required
  • CHECK: Age must be 18+, balance cannot be negative

Why Constraints Matter

All Constraints Summary
ConstraintPurposeExample
PRIMARY KEYUnique identifieruser_id
FOREIGN KEYLink tablescustomer_id references customers
UNIQUENo duplicatesemail, username
NOT NULLRequired fieldname, email
CHECKValidate valuesage >= 18, price > 0
5 rows

Without constraints:

  • Can create two users with same email (confusion!)
  • Can have age = -5 (impossible!)
  • Can have empty usernames (incomplete data!)

With constraints:

  • Database blocks bad data automatically
  • Keeps data clean and reliable
  • Prevents mistakes

Summary

All Constraints Summary
ConstraintPurposeExample
PRIMARY KEYUnique identifieruser_id
FOREIGN KEYLink tablescustomer_id references customers
UNIQUENo duplicatesemail, username
NOT NULLRequired fieldname, email
CHECKValidate valuesage >= 18, price > 0
5 rows

Constraints = Rules to protect data quality

  • PRIMARY KEY: Unique ID
  • FOREIGN KEY: Connect tables
  • UNIQUE: No duplicates
  • NOT NULL: Required fields
  • CHECK: Validate values

All working together to keep your database perfect!

Finished this topic?

Mark it complete to track your progress and maintain your streak!