Thuta Learning
SQL
AdvancedData & DatabasesBeginner

Constraints

SQLLesson 2430 min

What you'll walk away with

  • Write the six constraint kinds in both column-level and table-level form
  • Explain why UNIQUE and CHECK accept NULL, and when to pair them with NOT NULL
  • Choose a foreign key's ON DELETE action: RESTRICT, CASCADE or SET NULL
  • Name constraints and read duplicate-key, foreign-key and check-violation errors

Explain it simply

Constraints in plain language

A constraint is a rule attached to a table. The database checks every INSERT and UPDATE against its rules and rejects any row that breaks one. So even if the app has a bug, or a developer writes straight from psql, bad data cannot get into the table.

Think of the security gate at an airport. Whichever corridor a passenger arrives from, they must pass the gate and get checked. Validation in a form is like a question at the check-in counter; a constraint is the gate nobody can walk around.

Problem → Why → Solution

The problem: the app validates, yet bad data gets in

The shop app's order form blocks negative amounts and checks that the customer exists. Yet the month-end report shows orders for customer_id 99, who does not exist, two rows with the same order number, and an order of -5. A CSV import script and an admin's manual UPDATE never went through the form at all.

Without rules on the table, the database accepts whatever value it is given.

orders-without-rules.sql
CREATE TABLE orders (
    order_id     integer,
    order_number integer,
    customer_id  integer,
    amount       numeric(10, 2)
);

-- every one of these is accepted
INSERT INTO orders VALUES (1, 1001, 99, 25.00);  -- customer 99 does not exist
INSERT INTO orders VALUES (2, 1001, 1, 10.00);   -- duplicate order number
INSERT INTO orders VALUES (2, 1003, 1, -5.00);   -- duplicate id, negative amount

Why app validation alone is not enough

Data arrives by many routes: several app servers, background jobs, import scripts, migrations and hand-typed SQL. Repeating a rule on every route guarantees that one route forgets it. A constraint keeps the rule in the one place all the data lives, so every route is covered. It also wins races: when two requests arrive at the same moment, UNIQUE lets only one of them succeed.

Core concept: six rules and how they meet NULL

ConstraintWhat it blocks
NOT NULLa missing (NULL) value
UNIQUErepeated non-NULL values
PRIMARY KEYNULL and repeats; one per table
FOREIGN KEYa value missing from the referenced table
CHECK (expr)rows where expr is false
DEFAULT valuenothing; fills an omitted column

A constraint can be written right after its column (column-level) or as a separate item at the end of the column list (table-level). Rules that span two columns, such as PRIMARY KEY (order_id, line_no) or UNIQUE (product_id, reviewer_email), can only be table-level. A PRIMARY KEY behaves like UNIQUE plus NOT NULL, and PostgreSQL builds an index automatically for every primary key and unique constraint.

NULL means 'unknown', so the rules treat it specially. CHECK (amount > 0) evaluates to unknown for a NULL amount, and CHECK rejects only false, so the row is accepted. UNIQUE treats two NULLs as different, so any number of NULL rows get in; since PostgreSQL 15 you can change that with UNIQUE NULLS NOT DISTINCT. A NULL foreign-key column is not checked at all. Whenever a value is truly required, add NOT NULL as well.

A DEFAULT applies only when the column is left out of the INSERT entirely. Writing NULL explicitly stores NULL and ignores the default. For a foreign key, the referenced column must be a PRIMARY KEY or UNIQUE, and ON DELETE decides what happens when a parent row is deleted: the default NO ACTION (or RESTRICT) refuses, CASCADE deletes the child rows too, and SET NULL clears the child column. Choose the action per relationship by asking whether the child can exist on its own once its parent is gone.

What happens when a row arrives
  1. DEFAULT fills omitted columns
  2. NOT NULL and CHECK test the row
  3. UNIQUE/PK are checked via an index
  4. FOREIGN KEY looks up the parent row
  5. Any failure rejects the statement

In a multi-row INSERT, one failing row rolls back the whole statement, so none of the rows get in.

General pattern

sql
CREATE TABLE child_table (
    id_column   integer PRIMARY KEY,
    some_column type NOT NULL UNIQUE,
    other_col   type DEFAULT default_value,
    number_col  numeric CONSTRAINT rule_name CHECK (number_col > 0),
    parent_id   integer NOT NULL
        REFERENCES parent_table (parent_key) ON DELETE action,
    UNIQUE (column_a, column_b)
);

Write single-column rules after the column and multi-column rules at the end. Naming a rule with CONSTRAINT rule_name puts that name in error messages and makes ALTER TABLE ... DROP CONSTRAINT rule_name easy later.

Worked example: an orders table with rules

The customers table already holds two customers. The orders table below uses all six kinds of constraint, writing the primary key and the foreign key in table-level form. The INSERT leaves out order_status, and the SELECT shows the default filling it in.

orders-constraints.sql
CREATE TABLE orders (
    order_id     integer NOT NULL,
    order_number integer NOT NULL UNIQUE,
    customer_id  integer,
    order_status varchar(50) DEFAULT 'pending',
    amount       numeric(10, 2) NOT NULL CHECK (amount > 0),
    PRIMARY KEY (order_id),
    FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
);

INSERT INTO orders (order_id, order_number, customer_id, amount)
VALUES (1, 1001, 1, 25.00);

SELECT order_id, order_number, customer_id, order_status, amount
FROM orders;

Code breakdown

  1. Unique business numberorder_number integer NOT NULL UNIQUE,

    Customers quote the order number on the phone, so it must never repeat. Without NOT NULL, UNIQUE would let many NULL order numbers in, so both rules are combined.

  2. Default statusorder_status varchar(50) DEFAULT 'pending',

    If an INSERT does not mention order_status, it gets 'pending'. There is no NOT NULL here, so writing NULL explicitly would still store NULL.

  3. Business rule as CHECKamount numeric(10, 2) NOT NULL CHECK (amount > 0),

    Rejects zero and negative amounts. PostgreSQL names this rule orders_amount_check automatically.

  4. Table-level keysFOREIGN KEY (customer_id) REFERENCES customers (customer_id)

    Every customer_id must exist in customers. No ON DELETE action is given, so deleting a customer who still has orders is refused.

You should see
order_id | order_number | customer_id | order_status | amount
---------+--------------+-------------+--------------+-------
       1 |         1001 |           1 | pending      |  25.00

Reading the errors when a rule says no

Running each rule-breaking INSERT against the orders table above in psql produces the errors below. Every message names the constraint, so you know at once which rule fired. Application code can map the SQLSTATE code (23505 unique, 23503 foreign key, 23514 check, 23502 not null) to a friendly message for the user.

psql-session.txt
=> INSERT INTO orders (order_id, order_number, customer_id, amount)
   VALUES (2, 1001, 1, 5);
ERROR:  duplicate key value violates unique constraint "orders_order_number_key"

=> INSERT INTO orders (order_id, order_number, customer_id, amount)
   VALUES (2, 1002, 99, 5);
ERROR:  insert or update on table "orders" violates foreign key constraint
        "orders_customer_id_fkey"

=> INSERT INTO orders (order_id, order_number, customer_id, amount)
   VALUES (2, 1002, 1, -5);
ERROR:  new row for relation "orders" violates check constraint "orders_amount_check"

=> DELETE FROM customers WHERE customer_id = 1;
ERROR:  update or delete on table "customers" violates foreign key constraint
        "orders_customer_id_fkey" on table "orders"

When child rows should disappear with their parent, choose ON DELETE CASCADE. The order_items below are part of an order, so deleting the order should remove its items. Notice the two-column primary key and the named CHECK as well. The final SELECT shows items_left = 0.

order-items.sql
CREATE TABLE order_items (
    order_id integer NOT NULL
        REFERENCES orders (order_id) ON DELETE CASCADE,
    line_no  integer NOT NULL,
    quantity integer NOT NULL CONSTRAINT quantity_positive CHECK (quantity > 0),
    PRIMARY KEY (order_id, line_no)
);

INSERT INTO order_items VALUES (1, 1, 2), (1, 2, 1);

DELETE FROM orders WHERE order_id = 1;  -- its items go with it

SELECT count(*) AS items_left FROM order_items;

In real projects

Constraints in real projects

In production systems, constraints are the last line of defence for data. Form validation still exists to give users fast feedback, while the database rule is the real guarantee. ORMs such as Django, Prisma and SQLAlchemy turn model definitions like unique=True or ForeignKey into exactly these constraints in their migrations.

  • Checking for a duplicate email with a SELECT before sign-up has a race condition. A UNIQUE constraint plus INSERT ... ON CONFLICT (email) DO NOTHING, or catching error 23505, is what actually keeps emails unique.
  • Payment and inventory systems use rules such as CHECK (balance >= 0) and CHECK (stock >= 0) so that concurrent updates can never drive a value negative.
  • PostgreSQL does not create an index on a foreign key's child column automatically. Teams usually add one, such as an index on orders(customer_id), so that joins and parent deletes stay fast.

Common mistakes

Common constraint mistakes

Expecting UNIQUE or CHECK to block NULL

With email text UNIQUE, any number of users can have no email, and CHECK (rating BETWEEN 1 AND 5) accepts a NULL rating. When a value is required, add NOT NULL alongside.

Writing NULL and expecting the DEFAULT

VALUES (..., NULL, ...) stores NULL and ignores DEFAULT 'pending'. To get the default, leave the column out of the INSERT list or write the DEFAULT keyword in its place.

Putting ON DELETE CASCADE everywhere

With CASCADE from customers, deleting one customer wipes out their whole invoice history. Use CASCADE only when the child is part of the parent, like an order item, and keep the default refusal elsewhere.

Best practices

Best practices

  • Add the rules on the day you create the table; adding them after bad data has arrived means cleaning it up first.
  • For every column ask whether a missing value is acceptable, and make NOT NULL the default answer when it is not.
  • Give constraints meaningful names with CONSTRAINT, so error logs say which business rule fired.
  • Consider an index on every foreign-key child column.

Mini challenge

Mini challenge: products and reviews

Build two tables for a review system with full rules. Each user may review a product only once, and deleting a product must remove its reviews. Insert valid rows and show them with a join.

  • products: product_id primary key, sku NOT NULL UNIQUE, price numeric NOT NULL with a CHECK for price >= 0
  • products.status defaults to 'active' and allows only 'active' or 'archived'
  • reviews: product_id foreign key with ON DELETE CASCADE, rating NOT NULL with a 1-5 CHECK
  • Add UNIQUE (product_id, reviewer_email), insert rows and show them with a join
reviews-schema.sql
CREATE TABLE products (
    product_id integer,  -- TODO: primary key
    sku        text,     -- TODO: required and never repeated
    price      numeric(10, 2),  -- TODO: required, never negative
    status     text      -- TODO: default 'active'; only 'active' or 'archived'
);

CREATE TABLE reviews (
    review_id      integer,  -- TODO: primary key
    product_id     integer,  -- TODO: required, points at products, cascade on delete
    reviewer_email text,     -- TODO: required
    rating         integer   -- TODO: required, 1 to 5
    -- TODO: one review per product per reviewer
);

-- TODO: insert two products (leave status out) and three valid reviews
-- TODO: SELECT sku, status, reviewer_email, rating with a join

Expected: Three rows are shown, and both products have status 'active' from the default. A rating of 6, a repeated sku or a second review of one product by the same reviewer would be rejected.

Show hint

For status, a CHECK (status IN ('active', 'archived')) can sit next to the DEFAULT. The two-column UNIQUE must be written table-level, after the last column.

Show solution
reviews-schema.sql
CREATE TABLE products (
    product_id integer PRIMARY KEY,
    sku        text NOT NULL UNIQUE,
    price      numeric(10, 2) NOT NULL CHECK (price >= 0),
    status     text NOT NULL DEFAULT 'active'
               CHECK (status IN ('active', 'archived'))
);

CREATE TABLE reviews (
    review_id      integer PRIMARY KEY,
    product_id     integer NOT NULL
                   REFERENCES products (product_id) ON DELETE CASCADE,
    reviewer_email text NOT NULL,
    rating         integer NOT NULL CHECK (rating BETWEEN 1 AND 5),
    UNIQUE (product_id, reviewer_email)
);

INSERT INTO products (product_id, sku, price)
VALUES (1, 'TEA-100', 2.50), (2, 'MUG-200', 8.00);

INSERT INTO reviews VALUES
    (1, 1, 'aye@example.com', 5),
    (2, 1, 'bo@example.com', 4),
    (3, 2, 'aye@example.com', 3);

SELECT p.sku, p.status, r.reviewer_email, r.rating
FROM reviews AS r
JOIN products AS p ON p.product_id = r.product_id
ORDER BY r.review_id;

Quick quiz 1 / 3

The qty column of line_items has CHECK (qty > 0) but no NOT NULL. What does INSERT INTO line_items (qty) VALUES (NULL); do?

Quick quiz 2 / 3

order_status is varchar(50) DEFAULT 'pending'. After INSERT INTO orders (order_id, order_status) VALUES (5, NULL);, what is order_status?

Quick quiz 3 / 3

orders.customer_id references customers with no ON DELETE action. What happens when you DELETE customer 1, who still has orders?

What to remember

  • Constraints check every INSERT and UPDATE inside the database, so every route data takes is covered.
  • PRIMARY KEY means UNIQUE plus NOT NULL; FOREIGN KEY allows only values that exist in another table.
  • UNIQUE, CHECK and FOREIGN KEY all let NULL through, so pair them with NOT NULL when a value is required.
  • DEFAULT applies only when the column is omitted, and ON DELETE CASCADE belongs only where the child is part of the parent.

PostgreSQL SQL Tutorial — PostgreSQL Global Development Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Constraints | Thuta Learning