Sub topic 3
What Constraints Do and Why to Use Them
Assume you know basic SELECT, INSERT, UPDATE, and DELETE, and you understand tables, rows, columns, and common data types. This chapter focuses on the working model behind SQL constraints: rules the database checks before it accepts a change.
A constraint is a rule attached to a table or column. It defines which data is valid. When an INSERT or UPDATE would violate the rule, the database rejects the statement and reports an error. The invalid row is not partially saved.
Constraints protect data at its storage boundary. Application code can validate a form, but another script, administrator, import job, or service might write to the same database. A database constraint applies to all of them.
The main kinds of constraints
Each constraint protects a different property:
| Constraint | Protects | Typical question |
|---|---|---|
| `NOT NULL` | Required values | Must this column have a value? |
| `DEFAULT` | Initial values when omitted | What value should be supplied automatically? |
| `PRIMARY KEY` | Row identity | How is each row identified uniquely? |
| `UNIQUE` | Non-duplicate values | Which values must not repeat? |
| `FOREIGN KEY` | Relationships between tables | Must this reference an existing row? |
| `CHECK` | A condition on values | Does this value meet a business rule? |
DEFAULT supplies a value; it does not require one. For example, a default status of 'new' applies when the column is omitted, but it does not prevent someone from explicitly inserting another valid status. NOT NULL is the rule that prevents the stored value from being NULL.
A primary key is both unique and non-null. It identifies one row, while a separate UNIQUE constraint prevents duplicate values in a column such as an email address. A foreign key then uses a key in another table to preserve a relationship, such as an order belonging to an existing customer.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
total NUMERIC(10, 2) NOT NULL,
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id)
REFERENCES customers (customer_id),
CONSTRAINT ck_orders_total
CHECK (total >= 0)
);The orders table cannot contain an order for a missing customer. It also cannot contain a negative total. These rules express facts about the data rather than relying on every client to remember them.
Common errors
A constraint usually checks the value being written, not the intention behind it. Omitting a required column violates NOT NULL unless a DEFAULT supplies a value. Inserting an unknown foreign-key value fails even if the value looks like a valid identifier. A CHECK expression must account for SQL's three-valued logic: comparisons involving NULL can evaluate to unknown, so use NOT NULL when NULL must be forbidden.
Constraints are part of the schema, so they should be designed before loading data. They also provide reliable failure signals that application code can catch and handle.
Exercise
Which constraint should prevent an order from referring to a customer ID that does not exist, and what happens when an insert violates it?
Show answer
A FOREIGN KEY constraint should prevent it. The database rejects the INSERT and returns a constraint-violation error without storing the invalid row.