Constraints & Data Integrity — Database

A constraint is a rule on the table that the database enforces itself, so dirty data is rejected whichever way it comes in. NOT NULL must be filled in, UNIQUE…

In the Constraints & Validation lesson of the SQL track, an import script added data directly (without going through the app's form), and the result was two Budis with the same email. There's another gap, even when every piece of data comes through the form. Budi writes a review of Milk Coffee, then presses Send twice, very fast. Sunset Coffee's app does check "has Budi already reviewed Milk Coffee?" before saving, yet the review can still be saved twice.

What closes both gaps is a constraint: a rule attached to a table and enforced by the database itself. Data that breaks it is rejected, no matter where it comes from. Picture the ticket gates at a train station. The staff at the front may remind you "is there enough on your card?", but what actually stops a card with no balance is the gate's barrier. There is one at every entrance. Validation in the app is like that staff member. A constraint is like the gate's barrier, which stands at every path data takes into the table.

The reviews table and its rules

Sunset Coffee has a customers table (Budi id 1, Siti id 2) and a products table (Milk Coffee id 1, Palm Sugar Milk Coffee id 2). Now buyers can write reviews. The rules: a review must have an author and a product that really exist, the rating is 1 to 5, and one person may review each product only once. All of those rules are written directly into the table:

PRAGMA foreign_keys = ON;

CREATE TABLE reviews (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers(id),
  product_id INTEGER NOT NULL REFERENCES products(id),
  rating INTEGER NOT NULL CHECK (rating BETWEEN 1 AND 5),
  comment TEXT,
  status TEXT DEFAULT 'shown',
  UNIQUE (customer_id, product_id)
);

Four naughty requests, four rejections

These are the requests the app sends to the table above, with SQLite's answers as they are (the same ones the Lab shows). The -- lines are the answers:

INSERT INTO reviews (customer_id, product_id, rating, comment) VALUES (2, 1, 5, 'Just sweet enough');
-- saved, status filled in as 'shown'

INSERT INTO reviews (customer_id, product_id, rating, comment) VALUES (1, 1, 4, 'Great');
INSERT INTO reviews (customer_id, product_id, rating, comment) VALUES (1, 1, 4, 'Great');
-- the first is saved, the second gets:
-- UNIQUE constraint failed: reviews.customer_id, reviews.product_id

INSERT INTO reviews (customer_id, product_id, rating, comment) VALUES (1, 2, 6, 'Really tasty');
-- CHECK constraint failed: rating BETWEEN 1 AND 5

INSERT INTO reviews (product_id, rating) VALUES (2, 4);
-- NOT NULL constraint failed: reviews.customer_id

INSERT INTO reviews (customer_id, product_id, rating) VALUES (99, 2, 1);
-- FOREIGN KEY constraint failed

Why checking in the app isn't enough

A very fast double click sends two requests that run almost at the same time. The order can go like this:

Time Request A (first click) Request B (second click)
0 ms check: does Budi have a review for Milk Coffee? 0
1 ms check: does Budi have a review for Milk Coffee? 0
2 ms INSERT, saved
3 ms INSERT, saved too

Both requests check before either one saves, so both see 0. Without a constraint, Budi's review of Milk Coffee is saved 2 times. With UNIQUE (customer_id, product_id), the database checks at the very moment of saving, so the second INSERT is rejected. Data can also arrive without going through the form: an import script, an admin panel, or a manual query. A constraint guards all of those paths.

The check in the app is still useful for showing a friendly message ("You've already reviewed this product"). In Laravel, if the INSERT is still rejected by the UNIQUE rule, catch the error Illuminate\Database\UniqueConstraintViolationException (with try and catch), and show the same message.

UNIQUE and PRIMARY KEY

Both reject duplicate values, but the difference is clear:

PRIMARY KEY UNIQUE
May be NULL? No Yes, unless you add NOT NULL
How many per table? Only one As many as you like
Its job The identity of each row A business rule: email, the customer + product pair

So PRIMARY KEY = UNIQUE + NOT NULL, and only one per table. The customers table has the primary key id, and may have a UNIQUE on email and on phone at the same time. The database also creates an index for the primary key and for each UNIQUE automatically, so searching by those columns is fast.

In a Laravel migration

The same reviews table, written as a Laravel migration:

Schema::create('reviews', function (Blueprint $table) {
    $table->id();
    $table->foreignId('customer_id')->constrained();
    $table->foreignId('product_id')->constrained();
    $table->unsignedTinyInteger('rating');
    $table->text('comment')->nullable();
    $table->string('status')->default('shown');
    $table->unique(['customer_id', 'product_id']);
});

// in the customers table:
$table->string('email')->unique();

📌 The same messages in PostgreSQL

The rules are the same in PostgreSQL, only the wording of the errors differs. PostgreSQL names the constraint and shows the data:

ERROR:  duplicate key value violates unique constraint "reviews_customer_id_product_id_key"
DETAIL:  Key (customer_id, product_id)=(1, 1) already exists.

ERROR:  new row for relation "reviews" violates check constraint "reviews_rating_check"

ERROR:  insert or update on table "reviews" violates foreign key constraint "reviews_customer_id_fkey"
DETAIL:  Key (customer_id)=(99) is not present in table "customers".

PostgreSQL and MySQL (InnoDB) check FOREIGN KEYs without being switched on with a PRAGMA. MySQL only really enforces CHECK since version 8.0.16. Older versions accept a CHECK you write, and then quietly ignore it.

⚠️ Why doesn't the rule work the way you expected?

TL;DR: A constraint is a rule on the table that the database enforces itself, so dirty data is rejected whichever way it comes in. NOT NULL must be filled in, UNIQUE may not repeat (with two columns, the pair may not repeat). CHECK (condition) must be true, DEFAULT fills a column that isn't mentioned, and FOREIGN KEY (REFERENCES) makes sure the value exists in another table. A check in the app can fail against two requests that arrive at the same time. A constraint can't, because the database checks at the very moment of saving. PRIMARY KEY = UNIQUE + NOT NULL, only one per table. In Laravel: ->unique(), $table->unique([...]), ->constrained(), ->default().

⚡ Rules the database enforces

Write:

CREATE TABLE reviews (
  id INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers(id),
  product_id INTEGER NOT NULL REFERENCES products(id),
  rating INTEGER NOT NULL CHECK (rating BETWEEN 1 AND 5),
  comment TEXT,
  status TEXT DEFAULT 'shown',
  UNIQUE (customer_id, product_id)
);
Guess first: in this table, customer_id, product_id and rating must be filled in, they can't be empty. Which constraint makes a column required?

NOT NULL. A row that leaves the column empty is rejected with NOT NULL constraint failed.

Meaning: A constraint is a rule on the table that the database enforces itself: data that breaks it is rejected, no matter where it comes from. NOT NULL must be filled in, CHECK must be true, DEFAULT fills a column that isn't mentioned, and FOREIGN KEY (REFERENCES) makes sure the value exists in another table.

In the exercise, the constraint names must be spelled exactly: upper case, with the space in "NOT NULL" and "FOREIGN KEY".

⚡ UNIQUE on two columns

Write:

INSERT INTO reviews (customer_id, product_id, rating, comment) VALUES (1, 1, 4, 'Great');
INSERT INTO reviews (customer_id, product_id, rating, comment) VALUES (1, 1, 4, 'Great');
-- UNIQUE constraint failed: reviews.customer_id, reviews.product_id

Meaning: UNIQUE (customer_id, product_id) holds two columns, so what may not repeat is the pair. Here customer 1 is Budi, and product 1 is Milk Coffee. Budi may review many products, but the pair Budi + Milk Coffee may exist only once, so the second INSERT is rejected.

⚡ A check in the app isn't enough

Guess first: Budi presses Send twice, very fast. The app already checks for a duplicate review before saving. Without a constraint, how many reviews are saved?

Two. Each click sends one request, and both requests check before either one saves, so both see 0 reviews.

Meaning: With a UNIQUE constraint, the database checks at the very moment of saving, so the second INSERT is rejected. A constraint also guards every path data takes into the table, including import scripts and manual queries.

What you will learn