Sub topic 17
Putting it together: a small order-tracking schema
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), the common data types, and the individual constraints covered earlier: NOT NULL, DEFAULT, PRIMARY KEY, UNIQUE, FOREIGN KEY, and CHECK. Here you combine them into one schema, test it with bad data, and then change it with ALTER TABLE. The examples use PostgreSQL syntax. Differences in other systems are noted where they matter.
The design
The schema tracks customers who place orders. Each order contains one or more products.
- A customer has many orders.
- An order belongs to exactly one customer.
- An order has many products, and a product appears in many orders.
The last relationship is many-to-many. A relational database models it with a junction table, here order_items, that holds one row per product in each order.
Creating the tables in dependency order
A foreign key can only point to a table that already exists. Create parent tables first, then the tables that reference them: customers and products, then orders, then order_items.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE products (
product_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price NUMERIC(10, 2) NOT NULL CHECK (price >= 0)
);
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,
CONSTRAINT pk_orders PRIMARY KEY (order_id),
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
ON DELETE RESTRICT,
CONSTRAINT ck_orders_total CHECK (total_amount >= 0),
CONSTRAINT ck_orders_status
CHECK (status IN ('new', 'paid', 'shipped', 'cancelled'))
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES orders (order_id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products (product_id)
);Why each constraint is there
| Table | Constraint | Rule it enforces |
|---|---|---|
| customers | PRIMARY KEY on `customer_id` | Every customer has a unique, non-null identifier |
| customers | UNIQUE and NOT NULL on `email` | Two customers cannot share an email, and every customer has one |
| customers | DEFAULT on `created_at` | The creation time is filled in when the INSERT omits it |
| products | CHECK on `price` | A price cannot be negative |
| orders | NOT NULL on `customer_id` | An order cannot exist without a customer |
| orders | FOREIGN KEY with ON DELETE RESTRICT | A customer who still has orders cannot be deleted |
| orders | CHECK on `status` | Status must be one of four known values |
| orders | DEFAULT `'new'` on `status` | New orders start in the `new` state |
| order_items | Composite PRIMARY KEY | A product appears at most once per order |
| order_items | FOREIGN KEY with ON DELETE CASCADE | Deleting an order removes its items |
| order_items | CHECK on `quantity` | Quantity is at least 1 |
The two foreign keys on orders and order_items use different referential actions on purpose. Orders are business records, so the database refuses to delete a customer who owns any. Order items have no meaning without their order, so they follow it when it is deleted. The foreign key from order_items to products has no action specified. The default, NO ACTION, rejects deleting a product that appears in any order.
Design decisions worth noticing
- Key columns are NOT NULL. A primary key column is implicitly NOT NULL. Foreign key columns such as
customer_idneed an explicit NOT NULL. Without it, a foreign key column accepts NULL, and the database skips the reference check for that row. Here that would allow orders with no customer. - Money uses NUMERIC.
NUMERIC(10, 2)stores exact decimal values. Floating-point types can introduce rounding errors in sums. - Status is a CHECK list. This keeps the schema simple. If statuses change often, a separate lookup table with a foreign key is easier to maintain.
total_amountis stored. This duplicates information that could be computed fromorder_itemsandproducts.price. Storing it makes reads fast but lets the value drift out of sync. The database cannot check this with a simple CHECK, because CHECK cannot read other tables. The application, a trigger, or a generated view has to keep it consistent. A real design would also store the price on each order item, so later price changes do not rewrite history.
Testing the constraints
A schema is only trustworthy if you have seen it reject bad data. Insert valid rows first, then try to break each rule.
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', 'Ada Lovelace');
INSERT INTO products (name, price)
VALUES ('Notebook', 4.50);
INSERT INTO orders (customer_id, total_amount)
VALUES (1, 9.00);
INSERT INTO order_items (order_id, product_id, quantity)
VALUES (1, 1, 2);These statements succeed on a fresh database, where the identity columns start at 1. The order's status becomes 'new' through its default. Now try bad inserts.
-- Duplicate email violates UNIQUE
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', 'Another Ada');
-- No such customer violates the foreign key
INSERT INTO orders (customer_id, total_amount)
VALUES (9999, 10.00);
-- Negative total violates the CHECK
INSERT INTO orders (customer_id, total_amount)
VALUES (1, -5.00);
-- Same product twice in one order violates the composite primary key
INSERT INTO order_items (order_id, product_id, quantity)
VALUES (1, 1, 1);
-- Unknown status violates ck_orders_status
UPDATE orders SET status = 'lost' WHERE order_id = 1;Each statement fails and leaves the data unchanged. Because the constraints are named, PostgreSQL's error message points to the rule, for example new row for relation "orders" violates check constraint "ck_orders_total". The unnamed constraints get generated names such as customers_email_key, which are harder to read and not guaranteed to be the same across systems.
Now test the referential actions.
-- Rejected by ON DELETE RESTRICT: customer 1 still has an order
DELETE FROM customers WHERE customer_id = 1;
-- Allowed: the order's items are deleted along with it
DELETE FROM orders WHERE order_id = 1;
SELECT * FROM order_items; -- returns no rowsChanging the schema with ALTER TABLE
Requirements change. Suppose the business wants a cap on order totals, then drops it. Named constraints make both steps one statement.
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 validates every existing row first. If any row already violates it, the statement fails and the constraint is not added. Clean up or correct the data, then retry. The exact DROP syntax varies. PostgreSQL and SQL Server use DROP CONSTRAINT name. MySQL uses DROP CHECK name for check constraints and DROP FOREIGN KEY name for foreign keys.
Common mistakes
- Creating tables in the wrong order. A foreign key to a table that does not exist yet raises an error. When dropping, reverse the order: children before parents.
- Forgetting NOT NULL on a foreign key column. The column then accepts NULL and the relationship becomes optional.
- Expecting CHECK to compare against other tables. CHECK sees only the current row. Use foreign keys, triggers, or application logic for cross-table rules.
- Assuming every system enforces everything. MySQL before 8.0.16 parsed CHECK constraints but ignored them. SQLite does not enforce foreign keys unless you run
PRAGMA foreign_keys = ONon each connection. Test the rules on your actual database. - Using
ON DELETE CASCADEeverywhere. A cascade onorders.customer_idwould let one customer deletion silently erase their entire order history.
Dialect adjustments
To run this schema on other systems, change the identity syntax.
| System | Identity column definition |
|---|---|
| PostgreSQL | `INTEGER GENERATED ALWAYS AS IDENTITY` |
| MySQL | `INTEGER AUTO_INCREMENT` |
| SQL Server | `INTEGER IDENTITY(1,1)` |
MySQL and SQL Server also use different timestamp types and defaults in some cases (DATETIME2 is the usual SQL Server type). The constraint syntax itself is largely portable.
Exercise
In the schema above, a developer runs INSERT INTO orders (customer_id, total_amount) VALUES (NULL, 20.00);. Which constraint rejects it, and what would change if the NOT NULL were removed from customer_id?
Show answer
The NOT NULL constraint on customer_id rejects it. If NOT NULL were removed, the insert would succeed, because a foreign key is not checked when its column is NULL. The result would be an order with no customer.
Exercise
Write the ALTER TABLE statement that adds a CHECK constraint named ck_products_name_not_empty to products, requiring that name is not an empty string. Then explain what happens if a product with an empty name already exists.
Show answer
ALTER TABLE products ADD CONSTRAINT ckproductsnamenotempty CHECK (name <> ''); If a row with an empty name already exists, the statement fails because the database validates existing rows, and the constraint is not added until that row is fixed or removed.
Exercise
Customer 1 has an order, and that order has two rows in order_items. You run DELETE FROM orders WHERE order_id = 1; and then DELETE FROM customers WHERE customer_id = 1;. What happens in each statement, and why?
Show answer
The first statement succeeds. ON DELETE CASCADE on order_items.order_id deletes the two item rows along with the order. The second statement then succeeds too, because no orders reference the customer any more and ON DELETE RESTRICT has nothing to block. If the customer had another order, the second statement would be rejected.