Enforcing Data Integrity Rules in SQL

Data Integrity is the cornerstone of a reliable database. It ensures that data is accurate, consistent, and trustworthy. In this chapter, we explore the principles and techniques to enforce data integrity rules in SQL. From basic constraints to advanced validations, this chapter provides comprehensive coverage of ensuring data integrity in SQL databases.

Introduction to Data Integrity

What Is Data Integrity?

Data integrity refers to the accuracy and consistency of data stored in a database. It ensures that data remains valid, reliable, and protected from corruption or unauthorized changes.

 Importance of Data Integrity

  • Accuracy: Ensures data correctness.
  • Consistency: Maintains uniform data across the database.
  • Reliability: Builds trust in the data.
  • Compliance: Ensures adherence to business and regulatory rules.

Types of Data Integrity

Entity Integrity

Ensures that each record in a table is uniquely identifiable. This is typically enforced through primary keys.

Example:

				
					CREATE TABLE customers (
    customer_id INT PRIMARY KEY,
    name VARCHAR(100) NOT NULL
);

				
			

Referential Integrity

Maintains consistency between tables using foreign keys to establish relationships.

Example:

				
					CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

				
			

Domain Integrity

Ensures data falls within a valid range, format, or type. This is achieved using constraints like CHECK, NOT NULL, and data types.

Example:

				
					CREATE TABLE employees (
    emp_id INT PRIMARY KEY,
    age INT CHECK (age >= 18 AND age <= 65)
);

				
			

User-Defined Integrity

Business-specific rules enforced through triggers, stored procedures, or application logic.

Example:

				
					CREATE OR REPLACE FUNCTION validate_salary()
RETURNS TRIGGER AS $$
BEGIN
    IF NEW.salary < 3000 THEN
        RAISE EXCEPTION 'Salary must be at least 3000';
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER salary_check
BEFORE INSERT OR UPDATE ON employees
FOR EACH ROW EXECUTE FUNCTION validate_salary();

				
			

Constraints for Enforcing Data Integrity

Primary Key

A combination of NOT NULL and UNIQUE, used to uniquely identify records.

Example:

				
					CREATE TABLE products (
    product_id INT PRIMARY KEY,
    product_name VARCHAR(100) NOT NULL
);

				
			

Foreign Key

Ensures a valid relationship between two tables.

Example:

				
					CREATE TABLE invoices (
    invoice_id INT PRIMARY KEY,
    order_id INT,
    FOREIGN KEY (order_id) REFERENCES orders(order_id)
);

				
			

UNIQUE

Ensures that all values in a column are unique.

Example:

				
					CREATE TABLE users (
    user_id INT PRIMARY KEY,
    email VARCHAR(100) UNIQUE
);

				
			

NOT NULL

Prevents a column from containing NULL values.

Example

				
					CREATE TABLE users (
    user_id INT PRIMARY KEY,
    email VARCHAR(100) UNIQUE
);

				
			

CHECK

Validates data against a condition.

Example:

				
					CREATE TABLE inventory (
    item_id INT PRIMARY KEY,
    quantity INT CHECK (quantity >= 0)
);

				
			

DEFAULT

Assigns a default value to a column.

Example:

				
					CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    status VARCHAR(20) DEFAULT 'Pending'
);

				
			

Advanced Techniques for Enforcing Data Integrity

Using Triggers

Triggers allow complex validations by executing custom logic during INSERT, UPDATE, or DELETE operations.

Example

				
					CREATE OR REPLACE FUNCTION prevent_deletion()
RETURNS TRIGGER AS $$
BEGIN
    RAISE EXCEPTION 'Deletion is not allowed!';
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER delete_prevention
BEFORE DELETE ON customers
FOR EACH ROW EXECUTE FUNCTION prevent_deletion();

				
			

Using Views with Constraints

Views can enforce read-only integrity or derived data checks.

Example:

				
					CREATE VIEW valid_orders AS
SELECT * FROM orders
WHERE status IN ('Pending', 'Shipped');

				
			

Using Stored Procedures

Procedures encapsulate logic for data validation.

Example:

				
					CREATE PROCEDURE validate_order (IN order_id INT)
BEGIN
    IF NOT EXISTS (SELECT 1 FROM orders WHERE order_id = order_id) THEN
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Order does not exist!';
    END IF;
END;

				
			

Validating Data During Transactions

Deferred Constraint Validation

Some databases allow constraints to be deferred until the transaction is committed.

Example (PostgreSQL):

				
					ALTER TABLE orders ADD CONSTRAINT fk_customer DEFERRABLE INITIALLY DEFERRED;

				
			

Using Transactions for Integrity

Transactions group multiple operations into an atomic unit.

Example

				
					BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;

				
			

Handling Data Integrity Violations

Error Messages

When constraints are violated, SQL generates errors. Handling these errors ensures smooth user experiences.

Example

				
					INSERT INTO employees (emp_id, age) VALUES (1, 17);
-- Error: CHECK constraint "age_check" violated

				
			

Logging Violations

Capture violations for debugging or reporting.

Example

				
					CREATE OR REPLACE FUNCTION log_violation()
RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO error_logs (error_message) VALUES (TG_ARGV[0]);
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER violation_logger
AFTER INSERT OR UPDATE OR DELETE ON employees
FOR EACH ROW EXECUTE FUNCTION log_violation();

				
			

Best Practices for Enforcing Data Integrity

  1. Use Built-In Constraints: Utilize PRIMARY KEY, FOREIGN KEY, CHECK, and others whenever possible.
  2. Avoid Redundant Constraints: Ensure constraints do not overlap unnecessarily.
  3. Leverage Database Features: Use triggers, views, and stored procedures for advanced rules.
  4. Test Constraints: Validate against realistic data scenarios.
  5. Document Rules: Maintain clear documentation of data integrity rules.

Enforcing data integrity rules is a foundational aspect of database design and management. By applying the techniques and constraints discussed in this chapter, you ensure accurate, consistent, and reliable data. Understanding and utilizing these tools effectively allows you to build robust databases that maintain their integrity even under complex operations. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India