SQL Constraints: NOT NULL, UNIQUE, CHECK & DEFAULT Rules

Data integrity is the paramount responsibility of any database system. SQL Constraints are declarative rules enforced by the database engine on table columns to prevent invalid, corrupted, or duplicate data from ever being written. If an INSERT or UPDATE violates a constraint, the database aborts the statement and raises an error.


The 6 Essential SQL Constraints

• NOT NULL: Ensures that a column can never store empty NULL values.

• UNIQUE: Ensures that all values in a column are distinct across all rows.

• PRIMARY KEY: A combination of NOT NULL and UNIQUE that uniquely identifies each row.

• FOREIGN KEY: Enforces referential integrity between parent and child tables.

• CHECK: Validates that column values satisfy a boolean logical expression (e.g., salary > 0).

• DEFAULT: Automatically populates a default value if none is provided on insert.


Hands-on Example: Table with Multiple Constraints

CREATE TABLE employees (
    emp_id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    age INT NOT NULL,
    department VARCHAR(50) DEFAULT 'General',
    salary DECIMAL(10, 2) NOT NULL,
    status VARCHAR(20) DEFAULT 'Active',
    
    -- Table-Level CHECK Constraints
    CONSTRAINT chk_age CHECK (age >= 18 AND age <= 70),
    CONSTRAINT chk_salary CHECK (salary >= 15000.00),
    CONSTRAINT chk_status CHECK (status IN ('Active', 'On Leave', 'Terminated'))
);

Testing Constraint Violations (Engine Validation)

Let us test how the database engine safeguards integrity when invalid data is supplied:

-- Test 1: Violating the CHECK (age >= 18) constraint
INSERT INTO employees (first_name, email, age, salary)
VALUES ('Rahul', 'rahul@test.com', 16, 25000);
-- Result: ERROR 3819 (HY000): Check constraint 'chk_age' is violated.

-- Test 2: Violating the UNIQUE email constraint
INSERT INTO employees (first_name, email, age, salary)
VALUES ('Aman', 'aman@test.com', 24, 45000);

INSERT INTO employees (first_name, email, age, salary)
VALUES ('Pooja', 'aman@test.com', 26, 50000);
-- Result: ERROR 1062 (23000): Duplicate entry 'aman@test.com' for key 'employees.email'
Architectural Rule: Always name your constraints explicitly using CONSTRAINT constraint_name. This makes debugging easy in production application error logs.

Next, let us dive deep into the most critical constraint in relational modeling: SQL Primary Key!

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!