Sub topic 3
What constraints do and why to use them
This chapter assumes you can write basic SELECT, INSERT, UPDATE, and DELETE statements. It also assumes you know that a table is made of rows and columns, and that you recognize common data types such as integers, text, and timestamps. The examples use PostgreSQL syntax. Other systems differ in small ways, which a later chapter covers.
The problem constraints solve
A data type limits what kind of value a column holds. It does not limit which values are sensible. An INTEGER column accepts -5, and a VARCHAR column accepts an empty string or a duplicate email address. A table with only types will store any value of the right type.
Here is a table with types and nothing else:
CREATE TABLE accounts_loose (
account_id INTEGER,
email VARCHAR(255),
balance NUMERIC(10, 2)
);
INSERT INTO accounts_loose VALUES (1, '[email protected]', 50.00);
INSERT INTO accounts_loose VALUES (1, '[email protected]', -9999.00);
INSERT INTO accounts_loose VALUES (NULL, NULL, NULL);All three inserts succeed. The table now holds a duplicate ID, a duplicate email, a negative balance, and a row with no information at all.
A constraint is a rule attached to a table or column that the database checks on every change. If a change would break the rule, the database rejects the statement with an error and leaves the data as it was.
Why enforce rules in the database
You could validate in application code instead. That works until a second application, a data import script, or someone using a SQL console writes to the same table. Each of those paths has to repeat every rule correctly.
A constraint lives in the table, so every writer goes through it. This gives you three benefits:
- One place for each rule. You define it once, and no write path can skip it.
- No gap between check and write. An application that checks "is this email taken?" and then inserts can lose a race to another session. A unique constraint is checked as part of the write itself.
- Trustworthy reads. Queries can assume that
balanceis never negative or that every order has a customer. They don't need defensive code for impossible data.
Application validation is still useful for friendly error messages. Treat constraints as the last line of defense, not a replacement.
The constraint types at a glance
SQL has five main constraint types. Later chapters cover each in detail. This table is a map.
| Constraint | Rule it enforces |
|---|---|
| `NOT NULL` | The column must always have a value. |
| `PRIMARY KEY` | Each row has a unique, non-null identifier. |
| `UNIQUE` | No two rows may share the same value (or combination of values). |
| `FOREIGN KEY` | A value must match an existing row in another table. |
| `CHECK` | A condition you write must be true for the row. |
DEFAULT is often listed next to these but is not a constraint. It supplies a value when you omit one, and it never rejects anything.
Seeing constraints work
This table adds constraints to the earlier example:
CREATE TABLE accounts (
account_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
balance NUMERIC(10, 2) NOT NULL DEFAULT 0 CHECK (balance >= 0)
);
INSERT INTO accounts (email) VALUES ('[email protected]');The insert succeeds. The identity column generates account_id, and DEFAULT sets balance to 0. Now try statements that break the rules:
-- Duplicate email: violates UNIQUE
INSERT INTO accounts (email) VALUES ('[email protected]');
-- Negative balance: violates CHECK
INSERT INTO accounts (email, balance) VALUES ('[email protected]', -5);
-- Missing email: violates NOT NULL
INSERT INTO accounts (email) VALUES (NULL);
-- An UPDATE is checked too: this would make the balance -10
UPDATE accounts SET balance = balance - 10 WHERE email = '[email protected]';Each statement fails. In PostgreSQL the messages look like this:
ERROR: duplicate key value violates unique constraint "accounts_email_key"
ERROR: new row for relation "accounts" violates check constraint "accounts_balance_check"
ERROR: null value in column "email" of relation "accounts" violates not-null constraint
ERROR: new row for relation "accounts" violates check constraint "accounts_balance_check"The exact wording varies by database and version. Every message says which rule failed. Where the message includes a constraint name, it comes from the database because we did not supply one. A later chapter shows how to choose your own names so errors are easier to read.
How the check happens
The database tests constraints while it processes INSERT, UPDATE, and (for foreign keys) DELETE. If any constraint fails, the whole statement is rolled back, not just the offending row.
The checking order inside a real database is not guaranteed, so don't depend on which error appears first when a row breaks several rules.
Because the statement is all-or-nothing, a multi-row insert behaves like this:
INSERT INTO accounts (email, balance)
VALUES ('[email protected]', 10),
('[email protected]', -1);The second row violates the CHECK, so the database rejects the statement and neither row is stored.
Edge cases to know early
CHECK passes when the result is unknown. SQL uses three-valued logic. If balance were NULL, then balance >= 0 evaluates to unknown, not false, and a CHECK accepts unknown. The accounts table avoids this because balance is also NOT NULL. When a column must satisfy a CHECK, decide separately whether it may be NULL.
UNIQUE and NULL. Standard SQL treats two NULL values as not equal, so a UNIQUE column can hold many NULL rows. PostgreSQL and MySQL follow this. SQL Server allows only one NULL in a unique column.
Constraints don't fix existing data. Adding a constraint to a table that already holds rows that break it fails. You must clean the data first.
Constraints cost something. Each write does extra checking, and unique and primary keys are backed by an index that uses storage. This cost is usually small and worth paying. It is one reason to put rules on the data that truly must hold, not on every preference.
Choosing which rules to declare
A practical approach for each table:
- Give every table a primary key.
- Mark every column
NOT NULLunless "unknown" is a meaningful value for it. - Add
UNIQUEwhere real-world identifiers must not repeat, such as emails or SKUs. - Add
FOREIGN KEYwherever a column refers to a row in another table. - Add
CHECKfor simple rules that depend only on the row itself, such as ranges and allowed status values.
Rules that need data from many rows or other tables, such as "a customer may have at most five open orders", are not a good fit for CHECK. Handle those with other tools, such as triggers or application logic.
Exercise
A table has the column quantity INTEGER CHECK (quantity > 0) with no NOT NULL. A developer runs INSERT INTO order_items (quantity) VALUES (NULL); (other columns are omitted but satisfy their own rules). Does the CHECK reject the row? Why or why not, and how would you make the column reject it?
Show answer
The CHECK does not reject it. The expression NULL > 0 evaluates to unknown, and a CHECK constraint only rejects rows where the condition is false. To reject the row, declare the column NOT NULL as well: quantity INTEGER NOT NULL CHECK (quantity > 0).
Exercise
You run INSERT INTO accounts (email, balance) VALUES ('[email protected]', 5), ('[email protected]', -2); against the constrained accounts table. How many rows are stored afterward, and why?
Show answer
None. The second row violates CHECK (balance >= 0), and a statement that raises a constraint error is rolled back as a whole, so the first row is not stored either.