Sub topic 1
The example schema and the constraints that guard it
Every example in this tutorial runs against the same two tables, customers and orders. This chapter explains what each part of that schema does and which rule it enforces. Later chapters rely on those rules: a failed INSERT, a blocked DELETE, or an unexpected default all trace back to a definition in this chapter.
Prerequisites
This chapter assumes you already know:
- How to write a basic
SELECTwith aWHEREclause. - What tables, rows, and columns are.
- Common data types: integers, text, exact numbers, and timestamps.
- At a basic level, what a primary key and a foreign key are.
You need a database to run the examples. PostgreSQL, MySQL (InnoDB), SQL Server, and SQLite all work. Where they differ, the text says so.
The schema
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE,
status VARCHAR(20) NOT NULL DEFAULT 'active'
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (id),
total NUMERIC(10, 2) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new'
);customers is the parent table. orders is the child table, because each order points at one customer through customer_id. Create customers first. The foreign key in orders can only refer to a table that already exists.
What each constraint does
A constraint is a rule the database checks on every INSERT, UPDATE, and DELETE. If a change would break the rule, the database rejects the whole statement and changes nothing.
| Constraint | Where it appears | Rule it enforces |
|---|---|---|
| PRIMARY KEY | `customers.id`, `orders.id` | Each row has a value that is unique and never NULL |
| NOT NULL | `name`, `status`, `customer_id`, `total` | The column must always hold a value |
| UNIQUE | `customers.email` | No two rows may share the same non-NULL value |
| DEFAULT | `customers.status`, `orders.status` | A value used when an INSERT omits the column |
| FOREIGN KEY (REFERENCES) | `orders.customer_id` | The value must match an existing `customers.id` |
Primary key
The primary key identifies one row. An INSERT that repeats an existing id fails, and so does an UPDATE that would change an id to a value already in use. A primary key column also rejects NULL, even without an explicit NOT NULL.
In this schema you supply the id values yourself, so that the examples are easy to follow. In real systems you usually let the database generate them, with GENERATED ... AS IDENTITY (PostgreSQL, standard SQL), AUTO_INCREMENT (MySQL), IDENTITY (SQL Server), or INTEGER PRIMARY KEY in SQLite, where that column type auto-assigns values.
NOT NULL
NULL means "no value". A NOT NULL column rejects any attempt to store it. Two cases cause it:
- An INSERT that sets the column to NULL explicitly.
- An INSERT that omits the column when the column has no default.
In customers, name is NOT NULL and has no default. An INSERT that leaves out name therefore fails.
UNIQUE and NULL
email is UNIQUE but not NOT NULL. This combination has a subtle consequence: customers may have no email, and several of them may have none. Standard SQL treats NULLs as distinct from each other, so a UNIQUE column accepts any number of NULLs. PostgreSQL, MySQL, and SQLite follow this rule. SQL Server does not: its UNIQUE constraint allows only one NULL. If you need "unique when present" on SQL Server, use a filtered unique index.
Uniqueness comparisons can also depend on case. In PostgreSQL and SQLite, '[email protected]' and '[email protected]' count as different values. In MySQL and SQL Server, the default collation is case-insensitive, so those two values collide.
DEFAULT
A default fills in a column when the INSERT does not mention it. For customers.status, an INSERT that lists only id, name, and email produces a row with status 'active'.
Two points are easy to get wrong:
- A default applies only when the column is omitted, or when you write the keyword
DEFAULTin the VALUES list. If you writeNULLexplicitly, the database does not substitute the default. In a NOT NULL column that explicit NULL causes an error. - A default is not applied by UPDATE. An UPDATE changes only the columns you name in SET.
Foreign key
REFERENCES customers (id) says that every orders.customer_id must equal some existing customers.id. The database checks this rule in two directions:
- Inserting or updating a child row. You cannot create an order for a customer who does not exist.
- Deleting or updating a parent row. By default you cannot delete a customer who still has orders. Chapter 12 covers the other choices, such as
ON DELETE CASCADE.
Because customer_id is NOT NULL, every order must have a customer. Without NOT NULL, a foreign key column may be NULL, and a NULL is not checked against the parent table.
Dialect gotchas with foreign keys
Foreign keys are the constraint most likely to behave differently from what you expect.
- SQLite does not enforce foreign keys unless you turn them on for each connection with
PRAGMA foreign_keys = ON;. Without it, the schema above accepts orders for customers that do not exist. - MySQL parses an inline
REFERENCESclause in a column definition but ignores it. For MySQL, declare the key at table level instead, as shown below. The table must also use the InnoDB engine, which is the default in current versions. - PostgreSQL and SQL Server enforce the inline form as written.
This version of orders works everywhere, including MySQL:
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
total NUMERIC(10, 2) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new',
FOREIGN KEY (customer_id) REFERENCES customers (id)
);Seeing the constraints reject a change
Before you modify data, it helps to watch a constraint refuse a row. With the schema above in place, this statement fails because no customer has id 999:
INSERT INTO orders (id, customer_id, total)
VALUES (101, 999, 25.00);The error message names the broken rule. PostgreSQL reports violates foreign key constraint "orders_customer_id_fkey". MySQL reports error 1452, SQL Server reports error 547, and SQLite (with the pragma on) reports FOREIGN KEY constraint failed. Wording differs, but the effect is the same: the statement fails, and the orders table is unchanged.
A failed statement leaves no partial result. If a multi-row INSERT has one bad row, none of its rows are stored. The exception is a failure inside an open transaction. In PostgreSQL the transaction then enters an aborted state and you must roll back. Chapter 10 covers this.
Why this matters for the next chapters
Every statement in the rest of the tutorial meets these rules.
- INSERT must supply values for NOT NULL columns that have no default, and must not repeat a primary key or a unique email.
- UPDATE can break a constraint just as INSERT can. Setting
emailto one already in use fails. - DELETE is checked from the parent side. Removing a customer fails while orders still reference it.
Treat the constraints as a safety net, not a replacement for care. They block structurally invalid data, but they cannot tell that you updated the wrong 500 rows. The WHERE clause and transaction habits in later chapters cover that risk.
Exercise
A table is defined as CREATE TABLE members (id INTEGER PRIMARY KEY, email VARCHAR(255) UNIQUE, plan VARCHAR(20) NOT NULL DEFAULT 'free');. You run INSERT INTO members (id, email, plan) VALUES (1, NULL, NULL); and then INSERT INTO members (id) VALUES (2);. Which statements succeed in PostgreSQL, and what does row 2 contain?
Show answer
The first statement fails. It writes an explicit NULL into plan, which is NOT NULL, and the default is not substituted for an explicit NULL. The second statement succeeds. It omits email and plan, so email becomes NULL (allowed, since the column is nullable) and plan takes the default 'free'. Row 2 is (2, NULL, 'free'). Because UNIQUE accepts multiple NULLs in PostgreSQL, more rows with a NULL email could be added later. On SQL Server only one NULL email would be allowed.