Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 25 min · revision 3

Constraints as Executable Business Rules

Express business rules as NOT NULL, UNIQUE, CHECK and foreign-key constraints, choose referential actions on purpose, and denormalise through one enforced path.

Contentsand lesson path

What you will learn

  • Enforce business rules with NOT NULL, UNIQUE, CHECK and foreign-key actions, and justify any deliberate denormalization.

Prerequisites: SQL Fundamentals

01. Goal and setup

The normalisation lab left four clean tables; clean shape is only half the contract. The other half is rules: quantities are positive, statuses are real words, an order's customer must exist, and deleting a customer must not silently delete history. Written in application code, each rule holds only for the one program that implements it. Written as constraints, they hold for every writer — the API, a migration script, a late-night fix in psql.

You need: the rdm-lab container from the keys lesson and a psql session (docker exec -it rdm-lab psql -U postgres -d store). Run against PostgreSQL 17.12. Work in a database of your own:

SQL · store=#
DROP DATABASE IF EXISTS rulesdb;
CREATE DATABASE rulesdb;
\c rulesdb
Expected output (first run; later runs drop silently)
NOTICE:  database "rulesdb" does not exist, skipping
DROP DATABASE
CREATE DATABASE
You are now connected to database "rulesdb" as user "postgres".

02. Step 1: a schema that already knows the rules

This is the order schema from the worked example, tightened. Read the constraints as sentences: every price is positive; a status is one of four words; a customer with orders cannot be deleted; deleting an order takes its lines with it.

SQL · rulesdb=#
CREATE TABLE customers (
  id        bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email     text NOT NULL UNIQUE,
  full_name text NOT NULL
);

CREATE TABLE products (
  id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  sku   text NOT NULL UNIQUE,
  name  text NOT NULL,
  price numeric(10,2) NOT NULL CHECK (price > 0)
);

CREATE TABLE orders (
  id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  order_number text NOT NULL UNIQUE,
  customer_id  bigint NOT NULL REFERENCES customers(id) ON DELETE RESTRICT,
  status       text NOT NULL DEFAULT 'placed'
               CHECK (status IN ('placed', 'paid', 'shipped', 'cancelled')),
  placed_at    timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE order_lines (
  order_id   bigint NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
  line_no    integer NOT NULL,
  product_id bigint NOT NULL REFERENCES products(id),
  quantity   integer NOT NULL CHECK (quantity > 0),
  unit_price numeric(10,2) NOT NULL CHECK (unit_price >= 0),
  PRIMARY KEY (order_id, line_no)
);

INSERT INTO customers (email, full_name) VALUES
  ('[email protected]', 'Ana Petrova'),
  ('[email protected]', 'Liu Chen');

INSERT INTO products (sku, name, price) VALUES
  ('CBL-USBC-1M', 'USB-C cable 1m', 9.90),
  ('PAD-STD',     'Desk mat',      18.00);

INSERT INTO orders (order_number, customer_id) VALUES
  ('ORD-2026-0201', 1);

INSERT INTO order_lines (order_id, line_no, product_id, quantity, unit_price)
VALUES (1, 1, 1, 2, 9.90);
Expected output
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 2
INSERT 0 2
INSERT 0 1
INSERT 0 1

03. Step 2: NOT NULL and CHECK reject bad facts

NOT NULL states that a fact always exists; CHECK states what a legal value looks like. Try three writes that break them:

SQL · rulesdb=#
INSERT INTO order_lines (order_id, line_no, product_id, quantity)
VALUES (1, 2, 2, 1);

INSERT INTO order_lines (order_id, line_no, product_id, quantity, unit_price)
VALUES (1, 2, 2, 0, 18.00);

INSERT INTO orders (order_number, customer_id, status)
VALUES ('ORD-2026-0202', 1, 'dispatched');
Illustrative output (long lines wrapped; only the timestamp differs from your run)
ERROR:  null value in column "unit_price" of relation "order_lines"
        violates not-null constraint
DETAIL:  Failing row contains (1, 2, 2, 1, null).
ERROR:  new row for relation "order_lines" violates check constraint
        "order_lines_quantity_check"
DETAIL:  Failing row contains (1, 2, 2, 0, 18.00).
ERROR:  new row for relation "orders" violates check constraint "orders_status_check"
DETAIL:  Failing row contains (2, ORD-2026-0202, 1, dispatched,
         2026-11-26 11:39:44.980097+00).

Three rules, three loud failures, zero bad rows stored. Application-level validation is still worth having — it produces friendly errors and you test it as you learned in the testing skill — but it can never be the last line of defence, because the database accepts writes from more programs than yours. A CHECK crossing two columns of the same row works the same way, for instance CHECK (ends_at > starts_at) on a booking.

04. Step 3: UNIQUE rejects doubles

The uniqueness of a business identifier is itself a business rule, so it lives beside the key:

SQL · rulesdb=#
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', 'Ana clone');
Expected output
ERROR:  duplicate key value violates unique constraint "customers_email_key"
DETAIL:  Key (email)=([email protected]) already exists.

One subtlety is worth knowing because it surprises people: by default, UNIQUE treats NULL as never equal to anything, including another NULL, so many rows may hold NULL in a unique column. PostgreSQL 15 added UNIQUE NULLS NOT DISTINCT for the rarer rule "at most one row may leave this empty". Suppose a prices table where a NULL region means the default price: UNIQUE NULLS NOT DISTINCT (product_id, region) allows one price per region and only one default per product. An optional identifier such as a tax reference needs the opposite, the default behaviour, because many customers have none.

05. Step 4: foreign keys and referential actions

A foreign key rejects writes that point at nothing — and its referential action decides what happens to referencing rows when the referenced row is deleted. NO ACTION (the default) and RESTRICT refuse; CASCADE deletes the referencing rows too; SET NULL and SET DEFAULT detach them. First, a broken link:

SQL · rulesdb=#
INSERT INTO order_lines (order_id, line_no, product_id, quantity, unit_price)
VALUES (1, 2, 999, 1, 5.00);
Expected output (long lines wrapped)
ERROR:  insert or update on table "order_lines" violates foreign key
        constraint "order_lines_product_id_fkey"
DETAIL:  Key (product_id)=(999) is not present in table "products".

Now the two actions this schema chose on purpose. orders.customer_id is RESTRICT: deleting Ana while she has orders must fail, because order history outlives accounts. order_lines.order_id is CASCADE: a line without its order is meaningless, so deleting the order removes the lines:

SQL · rulesdb=#
DELETE FROM customers WHERE id = 1;
Expected output (long lines wrapped)
ERROR:  update or delete on table "customers" violates foreign key
        constraint "orders_customer_id_fkey" on table "orders"
DETAIL:  Key (id)=(1) is still referenced from table "orders".
SQL · rulesdb=#
SELECT count(*) AS lines_before FROM order_lines;

DELETE FROM orders WHERE id = 1;

SELECT count(*) AS lines_after FROM order_lines;
Expected output
 lines_before 
--------------
            1
(1 row)

DELETE 1
 lines_after 
-------------
           0
(1 row)

Choose the action per relationship, never as a global habit. CASCADE is right when the referencing row has no life of its own (lines in an order); RESTRICT or the default when it does (orders referencing a customer); SET NULL when the link is optional history. A cascade that deletes data the business needs to keep is one of the most expensive mistakes in schema design, because the rows are gone before anyone notices.

06. Step 5: denormalise deliberately, or not at all

Normalised tables answer questions by joining; a report that runs this join millions of times a day may genuinely benefit from storing one derived number, such as an order's item count. That is denormalisation: adding a redundant copy of a computable fact, buying read speed with write complexity. Before doing it, try the zero-risk option first — a view that computes the number on read, as the SQL views lesson showed. Denormalise only when measurement, not intuition, says the view is too slow.

If you do add the column, its defence is one enforced path that keeps it true. Here that path is a trigger:

SQL · rulesdb=#
ALTER TABLE orders ADD COLUMN item_count integer NOT NULL DEFAULT 0;

CREATE FUNCTION refresh_item_count() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
  target bigint;
BEGIN
  -- An UPDATE can move a line to another order: refresh both orders,
  -- in id order, so two concurrent moves lock their orders in one order.
  FOR target IN
    SELECT DISTINCT o FROM (VALUES (OLD.order_id), (NEW.order_id)) AS v(o)
     WHERE o IS NOT NULL ORDER BY o
  LOOP
    -- Lock the order row first: a concurrent writer of the same order
    -- finishes before we count, so the sum below sees its lines.
    -- NO KEY UPDATE, not UPDATE: it must not conflict with the KEY SHARE
    -- locks that foreign-key checks take on this row.
    PERFORM 1 FROM orders WHERE id = target FOR NO KEY UPDATE;
    UPDATE orders
       SET item_count = (SELECT COALESCE(sum(quantity), 0)
                           FROM order_lines WHERE order_id = target)
     WHERE id = target;
  END LOOP;
  RETURN NULL;
END;
$$;

CREATE TRIGGER order_lines_item_count
AFTER INSERT OR UPDATE OR DELETE ON order_lines
FOR EACH ROW EXECUTE FUNCTION refresh_item_count();
Expected output
ALTER TABLE
CREATE FUNCTION
CREATE TRIGGER

Every insert, update or delete of a line now recomputes the count of the order it touches inside the same statement — both orders, if an UPDATE moves a line from one order to another. The FOR NO KEY UPDATE line is not decoration. Without it, two transactions adding lines to the same order at the default READ COMMITTED level each count from a snapshot taken before the other committed: the second one waits for the row lock and then writes a total that leaves out the first one's line. Taking the lock before counting makes the second transaction wait first and count afterwards, with a fresh snapshot. The lock strength matters too: every insert into order_lines also takes a FOR KEY SHARE lock on its order for the foreign-key check, and plain FOR UPDATE conflicts with that lock, so two transactions adding lines to one order could each wait for the other's key-share lock and deadlock. FOR NO KEY UPDATE — the same lock an ordinary UPDATE of non-key columns takes — still serialises the counters but leaves foreign-key checks alone. A derived column maintained by a trigger needs the same concurrency care as any read-modify-write, which the lost updates lesson covers in depth. Test it on a fresh order — and note the id it reports:

SQL · rulesdb=#
INSERT INTO orders (order_number, customer_id, status)
VALUES ('ORD-2026-0203', 2, 'paid');

SELECT id, order_number, status, item_count FROM orders;
Expected output (your id may differ)
INSERT 0 1
 id | order_number  | status | item_count 
----+---------------+--------+------------
  3 | ORD-2026-0203 | paid   |          0
(1 row)

The id is 3 because the rejected insert in step 2 consumed identity value 2 — identity columns hand out values even to rows that fail, and gaps are normal, so never read meaning into them. Add two lines using the id you saw, then change and remove one:

SQL · rulesdb=# (3 is the id from the previous step)
INSERT INTO order_lines (order_id, line_no, product_id, quantity, unit_price) VALUES
  (3, 1, 1, 2,  9.90),
  (3, 2, 2, 1, 18.00);

SELECT order_number, status, item_count FROM orders;

UPDATE order_lines SET quantity = 4 WHERE order_id = 3 AND line_no = 2;

SELECT order_number, item_count FROM orders WHERE id = 3;

DELETE FROM order_lines WHERE order_id = 3 AND line_no = 2;

SELECT order_number, item_count FROM orders WHERE id = 3;
Expected output
INSERT 0 2
 order_number  | status | item_count 
---------------+--------+------------
 ORD-2026-0203 | paid   |          3
(1 row)

UPDATE 1
 order_number  | item_count 
---------------+------------
 ORD-2026-0203 |          6
(1 row)

DELETE 1
 order_number  | item_count 
---------------+------------
 ORD-2026-0203 |          2
(1 row)

The count follows every change without any application code knowing the column exists. Be honest about the cost in the schema's documentation: item_count is derived, the trigger is its only writer, and a direct UPDATE orders SET item_count = ... would still stick — a trigger guards a path, not the column. The justification for the whole arrangement is the measured read gain; without it, keep the view.

07. Troubleshooting

08. Check your understanding

Practice check · 3 questions

Rules and copies

Place rules in the schema and judge a derived column.

Q1. The rule "a booking must end after it starts" must hold for every program that writes. Where does it belong?
Q2. quantity > 0 lives in a CHECK on order_lines. A batch import inserts a line with quantity 0. What happens?
Q3. books.review_count is maintained by three different code paths. Which failure does this invite?
Practice only: not graded, not saved, not evidence.

09. Apply it

Close out the clinic practice with the constraints half of the deliverable:

  1. Write the clinic DDL with every business rule as a constraint: durations, working statuses, mandatory links, and the referential action for each relationship, chosen per pair.
  2. Write the five INSERT statements the constraints must reject — one per constraint type (NOT NULL, UNIQUE, CHECK, foreign key, referential action) — and run them, capturing each error.
  3. Choose one measured case where you would denormalise (say, a doctor's remaining slots today), and write the note justifying it: the read it unblocks, the single enforced path that maintains it, and the cost if that path is ever bypassed.

When you later move the schema into an application, the SQLAlchemy data access skill picks up exactly where this one ends, and versioned migrations get their own skill.

10. Review prompt

Without looking back: which constraint would you reach for to enforce a positive quantity, a single default price per product (a NULL region), a membership in a fixed list of statuses, and a link to a row that must exist? What do RESTRICT and CASCADE each do to referencing rows, and for which relationship in this lab was each the right call? Finally, name the two things that make a stored derived column defensible.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check