Sub topic 9
Constraints That Protect Data Integrity
Assume you already understand tables, data types, primary keys, foreign keys, and basic INSERT and SELECT statements. This chapter focuses on constraints: rules that a database checks before accepting a change.
Data integrity means that stored data remains accurate, consistent, and meaningful. Application code can check inputs, but database constraints provide a second line of defense. They protect the data even when a different application, script, or administrator writes to the database.
Common constraint types
A constraint is a rule attached to a table or column. If an INSERT or UPDATE violates the rule, the database rejects that change.
| Constraint | Protects against | Example |
|---|---|---|
| `NOT NULL` | Missing required values | Every order has an order date |
| `UNIQUE` | Duplicate values | Two customers share the same email |
| `CHECK` | Values outside a valid range | A quantity is zero or negative |
| `PRIMARY KEY` | Unidentified or duplicate rows | Two rows have the same ID |
| `FOREIGN KEY` | References to nonexistent rows | An order points to customer 99 when customer 99 does not exist |
Required values with `NOT NULL`
Use NOT NULL when a row cannot be useful without a value. For example, an order should have a date and a customer:
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
order_date DATE NOT NULL
);NOT NULL does not mean “the value must be nonempty.” For text, an empty string such as '' may still be accepted. If empty text is invalid, add a CHECK constraint or validate it in the application.
Uniqueness with `UNIQUE`
A UNIQUE constraint prevents two rows from having the same value:
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE
);This is useful for identifiers such as email addresses, usernames, or external reference numbers. Decide whether uniqueness should ignore letter case before choosing the database-specific design. Some systems treat [email protected] and [email protected] as different values.
Valid ranges with `CHECK`
A CHECK constraint evaluates a condition for each row:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) NOT NULL CHECK (price >= 0)
);The database rejects a negative price. Use constraints for rules that belong to the data model, such as nonnegative prices or positive quantities. Complex business rules involving several tables often need application logic, triggers, or a carefully designed transaction instead.
Foreign keys and referential integrity
A foreign key ensures that a value in one table refers to an existing key in another table:
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL
REFERENCES customers (customer_id),
order_date DATE NOT NULL
);Now an order cannot refer to a customer that does not exist. This protects referential integrity, which means relationships between tables remain valid.
When deleting or changing a referenced row, choose a policy deliberately. ON DELETE CASCADE deletes dependent rows automatically. ON DELETE RESTRICT rejects the deletion. ON DELETE SET NULL clears the foreign key, but the column must allow NULL.
Common errors
- Adding
NOT NULLto an existing column that already contains missing values. - Assuming
CHECK (amount >= 0)rejectsNULL. In SQL, aCHECKcondition that evaluates to unknown may pass, so combine it withNOT NULLwhen missing values are invalid. - Forgetting to enable foreign-key enforcement in database systems or connection settings that make it optional.
- Using
CASCADEwithout considering whether deleting one parent should remove historical records.
Design constraints around facts that must always be true. Then test both valid and invalid writes.
Exercise
Which constraints should a customer table use if every customer needs an ID, a name, and a unique email address?
Show answer
Use a PRIMARY KEY for the ID, NOT NULL for the name and email, and UNIQUE for the email. The email may need additional validation if its format matters.