Changing data and structure
Designing tables
Goal: Create tables with types, keys and constraints · 11 min
CREATE TABLE defines a table's columns, their types and constraints:
CREATE TABLE reviews (
id INTEGER PRIMARY KEY,
product_id INTEGER NOT NULL REFERENCES products(id),
stars INTEGER CHECK (stars BETWEEN 1 AND 5),
comment TEXT
);
- PRIMARY KEY — unique identifier of each row
- FOREIGN KEY / REFERENCES — must match an existing row in another table
- NOT NULL, UNIQUE, CHECK, DEFAULT — rules the database enforces
Good design (normalisation): store each fact once. Instead of a column "products" containing "Laptop, Mouse", create a separate table with one row per order item — exactly like order_items.
Worked example: A reviews table in use
- Create the table with a CHECK constraint.
- Insert two reviews.
- Average stars per product via JOIN.
CREATE TABLE reviews (id INTEGER PRIMARY KEY, product_id INTEGER NOT NULL REFERENCES products(id), stars INTEGER CHECK (stars BETWEEN 1 AND 5));
INSERT INTO reviews (product_id, stars) VALUES (1, 5), (1, 4);
SELECT p.name, AVG(r.stars) FROM reviews r JOIN products p ON p.id = r.product_id GROUP BY p.name;Output:
Laptop | 4.5