What are Integrity Constraints in SQL?

Abhishek Kumar Last Updated : 11 Jul, 2024
6 min read

Introduction

Imagine you’re the gatekeeper of a society where every resident and visitor must follow certain rules to maintain peace and order. In the world of databases, these rules are known as integrity constraints. Just as a society thrives when everyone abides by its laws, a database remains accurate and consistent when its data adheres to these crucial constraints. Intriguing, right? Further in this article, we will discuss integrity constraints in SQL.

Integrity Constraints in SQL

Overview

  • Integrity constraints in SQL ensure data accuracy and consistency like rules maintain order in a city.
  • Integrity constraints prevent data anomalies, ensuring valid and consistent data references.
  • The four main types are entity, domain, referential, and check constraints.
  • Practical examples show how these constraints improve data accuracy and consistency and reduce errors.
  • Integrity constraints are essential for a robust and reliable database system, safeguarding data integrity.

Why are Integrity Constraints Important?

Imagine a table storing information about customers and their orders. Without constraints, you might end up with an order referencing a non-existent customer! Integrity constraints help prevent such data anomalies by enforcing specific rules.

Types of Integrity Constraints in SQL

There are four main types of integrity constraints in SQL, each serving a specific purpose:

Type 1:Entity Integrity Constraints

These ensure each table row has a unique identifier, typically enforced through a primary key constraint. This is very helpful in preventing duplicate entries and guarantees a way to identify each record uniquely. We can also use that attribute to fetch data and organize data.

Example of Entity Integrity Constraints

E-commerce Order Table

  • Table Name: Orders
  • Columns:
    • OrderID (integer) Primary Key
    • CustomerID (integer)
    • OrderDate (date)
    • TotalAmount (decimal)

In this example, OrderID is the primary key. This ensures each order has a unique identifier, preventing duplicate order entries.

Type 2: Domain Constraints

These define the valid values for a particular column. For example, an age column might have a domain constraint restricting entries to NU. This ensures data conforms to the expected format and also unwanted entries in the data which may lead to more problems in the database.

Product Table

  • Table Name: Products
  • Columns:
    • ProductID (integer) Primary Key
    • ProductName (text)
    • Price (decimal) NOT NULL
    • StockLevel (integer) NOT NULL

Here, domain constraints are enforced on both Price and StockLevel columns. The NOT NULL constraints ensure the Price is not null.

Type 3: Referential Integrity Constraints

These maintain relationships between tables. A foreign key constraint creates a link between a column in one table (the foreign key) and the primary key of another table (the referenced table). This ensures data references in your database are valid and consistent.

Library Database

  • We can extend the library database to include a Bookshelves table:
    • Table Name: Bookshelves
    • Columns:
      • BookshelfID (integer) Primary Key
      • Location (text)
      • Capacity (integer)
    • We can add a foreign key constraint to the Books table:
      • Table Name: Books 
      • Columns:
        • Author (text)
        • Title (text)
        • ISBN (text) Primary Key
        • BookshelfID` (integer) FOREIGN KEY REFERENCES Bookshelves(BookshelfID)

In this scenario, the BookshelfID column in the Books table becomes a foreign key referencing the BookshelfID primary key in the Bookshelves table. This ensures a book record only references a valid bookshelf location.

Type 4: Check Constraints

These allow for more complex validation rules on a column or group of columns. You can define a custom expression that the data must adhere to. This offers greater flexibility for enforcing specific business logic within your database.

Product Table

  • Table Name: Products
  • Columns:
    • ProductID (integer) Primary Key
    • ProductName (text)
    • Price (decimal) CHECK (Price > 0)
    • StockLevel (integer) CHECK (StockLevel >= 0)

Here, domain constraints are enforced on both Price and StockLevel columns. The CHECK constraints ensure the Price is always positive and the StockLevel is never negative.

Also Read: SQL: A Full Fledged Guide from Basics to Advance Level

Benefits of Using Integrity Constraints

Here are the benefits of using integrity constraints:

  • Improved Data Accuracy: Prevent invalid or erroneous data from entering the database.
  • Enhanced Data Consistency: Ensure data adheres to defined rules, maintaining consistency across tables.
  • Reduced Errors: Enforce data validation rules, helping prevent errors during data manipulation.
  • Stronger Data Relationships: Referential constraints enforce relationships between tables, ensuring data references are valid.
  • Reliable Data Foundation: Safeguard the integrity of your data, leading to more trustworthy information.

Also read: Different Keys in SQL (Primary Key, Candidate Key, Foreign Key)

Understanding All Constraints With Examples

Now, we will use one more example to understand these constraints in better detail – Here, we have taken two tables, Departments and Employees, and we have used constraints.

-- Create tables

CREATE TABLE Departments (

    DeptID INT PRIMARY KEY,

    DeptName VARCHAR(50) UNIQUE NOT NULL

);

CREATE TABLE Employees (

    EmpID INT PRIMARY KEY,

    FirstName VARCHAR(50) NOT NULL,

    LastName VARCHAR(50) NOT NULL,

    Email VARCHAR(100) UNIQUE,

    Salary DECIMAL(10, 2) CHECK (Salary > 0),

    DeptID INT,

    FOREIGN KEY (DeptID) REFERENCES Departments(DeptID)

);

-- Insert sample data

INSERT INTO Departments (DeptID, DeptName) VALUES

(1, 'HR'),

(2, 'IT'),

(3, 'Finance');

INSERT INTO Employees (EmpID, FirstName, LastName, Email, Salary, DeptID) VALUES

(101, 'John', 'Doe', '[email protected]', 50000, 1),

(102, 'Jane', 'Smith', '[email protected]', 60000, 2),

(103, 'Mike', 'Johnson', '[email protected]', 55000, 3);
Integrity Constraints in SQL

Examples of Each Constraint

Now, let’s examine each constraint:

  1. Primary Key Constraint: Ensures a unique identifier for each record.

    This will fail due to duplicate primary key
INSERT INTO Departments (DeptID, DeptName) VALUES (1, 'Marketing');
Primary Key Constraint
  1. Foreign Key Constraint: Maintains referential integrity between tables.

This will fail due to the non-existent DeptID

INSERT INTO Employees (EmpID, FirstName, LastName, Email, Salary, DeptID)
VALUES (104, 'Alice', 'Brown', '[email protected]', 52000, 4);
Primary Key Constraint
  1. Unique Constraint: Ensures no duplicate values in a column.

    This will fail due to duplicate email
INSERT INTO Employees (EmpID, FirstName, LastName, Email, Salary, DeptID)
VALUES (105, 'Bob', 'Wilson', '[email protected]', 54000, 2);
Primary Key Constraint
  1. Check Constraint: Enforces domain integrity by limiting the values in a column.

This will fail due to negative salary

INSERT INTO Employees (EmpID, FirstName, LastName, Email, Salary, DeptID)
VALUES (106, 'Carol', 'Davis', '[email protected]', -1000, 3);
Primary Key Constraint
  1. Not Null Constraint: Ensures a column cannot have NULL values.

    This will fail due to NULL FirstName
INSERT INTO Employees (EmpID, FirstName, LastName, Email, Salary, DeptID)
VALUES (107, NULL, 'Taylor', '[email protected]', 58000, 1);
Primary Key Constraint

These integrity constraints work together to maintain data consistency and reliability in your database.

Also read: SQL For Data Science: A Beginner Guide!

Conclusion

So, we saw how integrity constraints help build a robust and reliable database system. These constraints act as a safety net, safeguarding the integrity of your data and ensuring its accuracy for future use. By enforcing rules that data must adhere to, they prevent errors and inconsistencies that could otherwise lead to significant issues. Whether it’s maintaining unique identifiers with primary keys, ensuring relationships with foreign keys, or enforcing specific data ranges with check constraints, these mechanisms are essential for the health and reliability of your database. As you design and manage your

Frequently Asked Questions

Q1. What are integrity constraints in SQL? 

Ans. Integrity constraints in SQL are rules that ensure data accuracy and consistency, and they:
A. Enforce data validation
B. Maintain relationships between tables
C. Prevent invalid data entry
D. Include Primary Key, Foreign Key, Unique, Check, and Not Null constraints

Q2. What are the 6 constraints in SQL? 

Ans. A: The six main constraints in SQL are:
A. Primary Key Constraint
B. Foreign Key Constraint
C. Unique Constraint
D. Check Constraint
E. Not Null Constraint
F. Default Constraint

Q3. What is the integrity of data in SQL? 

Ans. Data integrity in SQL means:
A. Data is accurate and consistent
B. Information remains reliable over time
C. Data is protected from unauthorized changes
D. Stored data matches its intended representation
E. Relationships between data elements are preserved

Q4. What is data integrity vs integrity constraints? 

Ans. Data integrity is the overall concept of maintaining accurate and consistent data, while integrity constraints are the specific rules implemented in SQL to enforce data integrity. In other words:
A. Data integrity is the goal of ensuring data is accurate, consistent, and reliable.
B. Integrity constraints are the means: specific rules and mechanisms in SQL that help achieve and maintain data integrity.
C. Integrity constraints are tools used to implement and enforce data integrity within a database management system.

Hello, I'm Abhishek, a Data Engineer Trainee at Analytics Vidhya. I'm passionate about data engineering and video games I have experience in Apache Hadoop, AWS, and SQL,and I keep on exploring their intricacies and optimizing data workflows 

Responses From Readers

Clear

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details