Sub topic 11
Enforcing Rules with CHECK
Assume you know basic SELECT, INSERT, UPDATE, and DELETE, and understand tables, rows, columns, and common data types. This chapter focuses on rules that validate values in one row.
A CHECK constraint is a condition that every stored row must satisfy. The database evaluates the condition when inserting or updating a row. If the condition is false, the statement is rejected.
Basic CHECK constraints
Suppose an order cannot have a negative amount, and its status must be one of a fixed set of values:
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
total_amount NUMERIC(10, 2) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new',
CONSTRAINT ck_orders_total
CHECK (total_amount >= 0),
CONSTRAINT ck_orders_status
CHECK (status IN ('new', 'paid', 'shipped', 'cancelled'))
);The first constraint checks a numeric comparison. The second checks membership in a list. Both constraints have names, so error messages and later schema changes can identify them clearly.
| Rule | Example condition | Rejects |
|---|---|---|
| Nonnegative amount | `total_amount >= 0` | `-5.00` |
| Allowed status | `status IN ('new', 'paid')` | `'refunded'` |
| Valid range | `rating BETWEEN 1 AND 5` | `0` or `6` |
A constraint applies during both INSERT and UPDATE:
INSERT INTO orders (order_id, total_amount, status)
VALUES (1, 25.00, 'paid');
-- Rejected: total_amount >= 0 is false.
INSERT INTO orders (order_id, total_amount, status)
VALUES (2, -5.00, 'new');
-- Rejected: status is not in the allowed list.
INSERT INTO orders (order_id, total_amount, status)
VALUES (3, 10.00, 'refunded');The failed statement does not store its invalid row. An application should still handle the database error and show a useful message to the user.
CHECK and NULL values
SQL conditions can produce TRUE, FALSE, or UNKNOWN. A CHECK constraint normally rejects only FALSE. Therefore, CHECK (discount >= 0) may allow a NULL discount because the comparison is UNKNOWN.
Use NOT NULL when the value must exist:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
price NUMERIC(10, 2) NOT NULL,
discount NUMERIC(10, 2) NOT NULL DEFAULT 0,
CONSTRAINT ck_products_price CHECK (price >= 0),
CONSTRAINT ck_products_discount CHECK (discount >= 0),
CONSTRAINT ck_products_discount_limit CHECK (discount <= price)
);This combination ensures that prices and discounts exist, are nonnegative, and do not exceed the price.
When CHECK is not enough
A rule such as “an order must reference an existing customer” requires a FOREIGN KEY. A rule such as “an email address must be unique” requires UNIQUE. A CHECK expression should describe a condition that can be evaluated from the current row without relying on another row.
Some systems differ in how strictly they enforce complex CHECK expressions or expressions involving functions. Keep checks deterministic and portable when multiple database systems are possible.
Exercise
What happens when this table receives a row with a NULL value for score? CREATE TABLE results ( score INTEGER CHECK (score >= 0 AND score <= 100) );
Show answer
The row may be accepted because the comparison with NULL produces UNKNOWN, which CHECK normally does not reject. Add NOT NULL if score is required.