Description

Constraints are rules applied to table columns. They enforce data integrity and accuracy, prevent invalid or inconsistent data, and keep database structures reliable. If a user tries to store data that violates a constraint, an error is raised.

Agenda

  • Types of constraints
  • Defining and modifying constraints
  • Best practices

Types of Constraints

CHECK, DEFAULT, NOT NULL, UNIQUE, PRIMARY KEY (including composite), FOREIGN KEY.

CHECK

Ensures that data in a column meets a particular condition. It enforces domain integrity and can define value ranges, formats, or logical relationships between columns. A condition must be true for each row.

-- Numeric range
CREATE TABLE employees (
    id     serial PRIMARY KEY,
    age    INT CHECK (age BETWEEN 18 AND 65),
    salary NUMERIC CHECK (salary > 0)
);

-- String pattern (e-mail format)
ALTER TABLE users ADD CONSTRAINT email_format
CHECK (email ~ '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$');

Regular expression parts: ^[A-Za-z0-9._%+-]+ allowed local-part characters; @ separator; [A-Za-z0-9.-]+ domain name; [A-Za-z]{2,}$ top-level domain with at least two letters.

-- Multiple-column constraint
CREATE TABLE bookings (
    start_date DATE,
    end_date   DATE,
    CONSTRAINT valid_period CHECK (end_date > start_date)
);

-- Function inside a constraint
ALTER TABLE products ADD CONSTRAINT name_not_blank CHECK (LENGTH(TRIM(name)) > 0);

-- Add / remove a CHECK on an existing table
ALTER TABLE employees ADD CONSTRAINT age_check CHECK (age >= 18);
ALTER TABLE employees DROP CONSTRAINT age_check;

A table can have multiple constraints at once (e.g., NOT NULL, CHECK and UNIQUE on the same column).

DEFAULT

Specifies a value used when none is supplied on INSERT.

  • Automatic assignment: if no value is given, the default is inserted.
  • Optional: without a default, the column is NULL (if nulls are allowed).
  • Flexible: the default can be a constant, an expression or a function (e.g., CURRENT_TIMESTAMP).
CREATE TABLE orders (
    id         serial PRIMARY KEY,
    status     VARCHAR(20) DEFAULT 'new',
    created_at TIMESTAMP   DEFAULT CURRENT_TIMESTAMP
);

NULL and NOT NULL

  • By default, columns allow NULL unless defined NOT NULL.
  • NULL means the absence of a value; it is different from an empty string or zero.
  • NOT NULL requires a value to always be present.
ALTER TABLE employees ALTER COLUMN first_name SET NOT NULL;   -- add
ALTER TABLE employees ALTER COLUMN first_name DROP NOT NULL;  -- remove

UNIQUE

Ensures all values in a column (or group of columns) are distinct.

CREATE TABLE users (id serial PRIMARY KEY, email VARCHAR(255) UNIQUE);
ALTER TABLE users ADD CONSTRAINT unique_email UNIQUE (email);  -- existing table
  • UNIQUE allows NULLs, and each NULL is treated as distinct, so multiple NULLs are allowed.
  • Unlike PRIMARY KEY, a table can have several UNIQUE constraints.

PRIMARY KEY and Composite Primary Key

A primary key is NOT NULL + UNIQUE. A composite primary key spans more than one column and uniquely identifies rows by the combination of values.

CREATE TABLE enrollment (
    student_id INT,
    course_id  INT,
    PRIMARY KEY (student_id, course_id)
);

FOREIGN KEY

Establishes a relationship between two tables by referencing the primary key of another table.

  • Referential integrity: prevents inserting child rows that do not exist in the parent table.
  • Links tables: creates the parent–child relationship.
  • Cascade options control what happens when the parent changes.
CREATE TABLE orders (
    order_id    serial PRIMARY KEY,
    customer_id INT REFERENCES customers (customer_id) ON DELETE CASCADE
);
OptionBehaviour
ON DELETE CASCADEDeleting a parent row deletes the related child rows
ON UPDATE CASCADEUpdating the referenced key updates the foreign key in child rows
ON DELETE SET NULLSets the child foreign key to NULL when the parent is deleted
ON DELETE RESTRICTPrevents deleting a parent row that is still referenced

Best Practices

  • Name constraints explicitly (CONSTRAINT name ...) so they are easy to drop or alter.
  • Enforce rules in the database, not only in application code.
  • Use NOT NULL for required fields, CHECK for domain rules, and foreign keys for relationships.
  • Choose cascade behaviour deliberately, since CASCADE can delete large amounts of data.

Conclusion

Constraints are the database's built-in guards: they make invalid data impossible to store and keep relationships between tables consistent.