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)
);
- NOT NULL: the column must be filled in.
NULLis the mark for "nothing in here". - FOREIGN KEY (
REFERENCES customers(id)): the value must exist in theidcolumn of another table, exactly as in the Primary Key & Foreign Key lesson. In SQLite the check only runs afterPRAGMA foreign_keys = ON;. - CHECK (
CHECK (rating BETWEEN 1 AND 5)): a rule of your own. The condition in the brackets must be true for every row.BETWEEN 1 AND 5means 1 to 5, including 1 and 5. - DEFAULT (
DEFAULT 'shown'): a default value. If anINSERTdoesn't mention thestatuscolumn, it gets'shown'. DEFAULT rejects nothing, it only fills in. - UNIQUE (
UNIQUE (customer_id, product_id)): no two rows may have the same value. Because it holds two columns, what may not repeat is the pair. Budi may review Milk Coffee and Palm Sugar Milk Coffee. Siti and Budi may both review Milk Coffee. But the pair Budi + Milk Coffee may exist only once.
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
- The error message names the kind of rule that was broken, then, except for FOREIGN KEY, the column or the condition. Read that message before guessing.
- A rejected
INSERTis cancelled completely. No half-made row is left behind. - The end result is just 2 rows: Siti's review and Budi's first review. Four pieces of dirty data never reach the table.
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();
- Laravel columns are
NOT NULLautomatically, unless you write->nullable(). ->constrained()makes a FOREIGN KEY to thecustomersandproductstables.->unique()on one column makes a UNIQUE for that column.$table->unique([...])with an array makes a combined UNIQUE.->default('shown')makes a DEFAULT.- Laravel's Blueprint (the
$tableobject in a migration) has no method for CHECK yet. On MySQL or PostgreSQL, write it withDB::statement('ALTER TABLE reviews ADD CONSTRAINT reviews_rating_check CHECK (rating BETWEEN 1 AND 5)');.
📌 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?
- CHECK lets NULL through. CHECK only rejects a row when its condition is false.
NULL BETWEEN 1 AND 5comes out as "unknown", not "false", so an empty rating still gets in. If the rating must be there, addNOT NULLtoo. - UNIQUE on the wrong column.
UNIQUE (customer_id)alone means Budi may review only one product, ever. What you meant is the pair(customer_id, product_id). - UNIQUE lets NULL through. In SQLite, PostgreSQL and MySQL, every
NULLcounts as different. So withoutNOT NULL,UNIQUE (customer_id, product_id)accepts two rows of(1, NULL). If the columns are required, addNOT NULL, as thereviewstable does. In PostgreSQL 15 and later, you can also writeUNIQUE NULLS NOT DISTINCT (customer_id, product_id), so thatNULLvalues count as equal. - Forgetting
PRAGMA foreign_keys = ONin SQLite. The FOREIGN KEY is on the table, but SQLite doesn't check it. - Adding a constraint to a table that's already dirty. If duplicate reviews already exist, creating the UNIQUE fails. Clean the data first, then add the rule.
- In the exercise, the constraint names must be spelled exactly: upper case, with the space in
"NOT NULL"and"FOREIGN KEY".
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.