Sub topic 3
Enforcing rules with CHECK
This chapter assumes you know basic SQL statements (SELECT, INSERT, UPDATE, DELETE) and the ideas of tables, rows, and columns. A CHECK constraint is a rule that every row must satisfy. The database rejects any INSERT or UPDATE that breaks the rule, so invalid data never gets stored.
Writing column-level and table-level constraints
A column-level constraint sits inside one column definition. A table-level constraint is listed after the columns, can be named, and can refer to several columns.
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY,
customer_id INTEGER NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new',
total_amount NUMERIC(10, 2) NOT NULL CHECK (total_amount >= 0),
CONSTRAINT pk_orders PRIMARY KEY (order_id),
CONSTRAINT ck_orders_status
CHECK (status IN ('new', 'paid', 'shipped', 'cancelled'))
);Naming constraints
Name constraints with CONSTRAINT name. When a rule fails, the error message usually includes that name, so ck_orders_status is easier to find than a system-generated name. A name also lets you drop or change the rule later.
Changing constraints with ALTER TABLE
Use ALTER TABLE to add or drop a named constraint on an existing table:
ALTER TABLE orders
ADD CONSTRAINT ck_orders_total_limit CHECK (total_amount <= 1000000);
ALTER TABLE orders
DROP CONSTRAINT ck_orders_total_limit;Adding a constraint fails if existing rows already break it.
How constraints relate to indexes
PRIMARY KEY and UNIQUE create an index automatically, so the database can find duplicates quickly. CHECK needs no index. FOREIGN KEY behavior varies. PostgreSQL does not index the referencing column automatically, so add an index yourself if you often filter or delete by that column.
Differences between database systems
- Identity columns: PostgreSQL uses
GENERATED ... AS IDENTITY, MySQL usesAUTO_INCREMENT, and SQL Server usesIDENTITY(1,1). - CHECK enforcement: MySQL versions before 8.0.16 accept CHECK but ignore it.
- Foreign keys: SQLite enforces them only after you run
PRAGMA foreign_keys = ON. - Dropping: MySQL uses
DROP CHECK namefor CHECK constraints.
> Test each constraint on your own database before you rely on it.
Putting it together: a small order-tracking schema
Create the parent table first, then the table that references it:
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new',
total_amount NUMERIC(10, 2) NOT NULL,
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id),
CONSTRAINT ck_orders_total CHECK (total_amount >= 0),
CONSTRAINT ck_orders_status
CHECK (status IN ('new', 'paid', 'shipped', 'cancelled'))
);Exercise
Which constraint rejects this statement, and why? INSERT INTO orders (customerid, status, totalamount) VALUES (1, 'lost', 5.00);
Show answer
ckordersstatus rejects it because 'lost' is not in the allowed status list. The error message names the constraint, which is why naming helps.