Constraint Validation is a crucial aspect of database management, ensuring that data integrity and accuracy are maintained. Constraints are rules enforced on database columns to ensure that only valid data is entered into a table. This chapter explores the types of constraints, their usage, and techniques for implementing, validating, and managing them in SQL.
NULL
values.Constraints can be added while creating a table:
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE,
age INT CHECK (age >= 18),
department_id INT,
FOREIGN KEY (department_id) REFERENCES departments(department_id)
);
Constraints can also be added to existing tables:
ALTER TABLE employees
ADD CONSTRAINT chk_age CHECK (age <= 60);
Ensures that a column cannot store NULL
values.
CREATE TABLE products (
product_id INT NOT NULL,
product_name VARCHAR(100) NOT NULL
);
product_id
and product_name
columns must have values; they cannot be empty.Ensures that all values in a column or combination of columns are unique.
CREATE TABLE users (
user_id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);
email
.A combination of NOT NULL
and UNIQUE
. It uniquely identifies each record in a table.
CREATE TABLE orders (
order_id INT PRIMARY KEY,
order_date DATE NOT NULL
);
order_id
must be unique and non-null, ensuring each order is identifiable.Links two tables and ensures referential integrity.
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
customer_id
in the orders
table must match a customer_id
in the customers
table.Ensures that column values satisfy a specific condition.
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
salary DECIMAL(10, 2) CHECK (salary > 0)
);
salary
column must always have a value greater than zero.Provides a default value for a column when no value is specified.
CREATE TABLE orders (
order_id INT PRIMARY KEY,
status VARCHAR(20) DEFAULT 'Pending'
);
status
, it defaults to 'Pending'
.Prevents certain combinations of column values from occurring.
CREATE TABLE reservations (
room_id INT,
reservation_date DATE,
EXCLUDE USING GIST (room_id WITH =, reservation_date WITH =)
);
Constraints are automatically enforced when inserting or updating data.
INSERT INTO employees (emp_id, name, age) VALUES (1, 'John', 17);
-- Error: Age must be greater than or equal to 18
Some databases allow deferring constraints until a transaction is committed.
ALTER TABLE orders ADD CONSTRAINT fk_customer DEFERRABLE INITIALLY DEFERRED;
For complex validations beyond constraints, use triggers.
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 can be removed if no longer needed.
ALTER TABLE employees DROP CONSTRAINT chk_age;
Some databases allow temporarily disabling constraints.
ALTER TABLE orders DISABLE CONSTRAINT fk_customer;
PRIMARY KEY
and UNIQUE
automatically create indexes, improving performance.Constraint validation techniques are fundamental to SQL database management. By enforcing rules like NOT NULL, UNIQUE, CHECK, and others, you ensure data integrity, reduce errors, and maintain consistency across your database.This chapter provided an in-depth look into constraints, their implementation, and advanced validation techniques. By mastering these concepts, you can build robust, error-resistant databases that meet the demands of modern applications. Happy coding !❤️