← All lessons
Advanced SQL · Lesson 9 of 11

Designing tables

Someone had to decide that the shop has a customers table with those columns. CREATE TABLE does it: a name, then each column with its type and any constraints, rules the database enforces on every insert and update.

CREATE TABLE reviews (
  id INTEGER PRIMARY KEY,
  product_id INTEGER NOT NULL REFERENCES products(id),
  stars INTEGER NOT NULL CHECK (stars BETWEEN 1 AND 5),
  email TEXT NOT NULL,
  written_on TEXT NOT NULL DEFAULT '2024-10-31',
  UNIQUE (product_id, email)
);
INSERT INTO reviews (id, product_id, stars, email) VALUES (1, 2, 5, '[email protected]'), (2, 2, 4, '[email protected]');

SELECT product_id, COUNT(*) AS reviews, AVG(stars) AS avg_stars, MIN(written_on) AS written_on FROM reviews GROUP BY product_id;
Returns
product_id | reviews | avg_stars | written_on
-----------+---------+-----------+-----------
2          | 2       | 4.5       | 2024-10-31
(1 row)

Each constraint stops a kind of bad data at the door:

  • PRIMARY KEY: every row has its own value, never NULL
  • NOT NULL: the column must be filled in
  • UNIQUE: no two rows share the value (here: one review per person per product)
  • CHECK (…): a rule each row must pass, like stars from 1 to 5
  • REFERENCES t(id): a foreign key; the value must exist in that table
  • DEFAULT …: what to store when an insert leaves the column out

Try to break one and the statement fails with an error, and nothing is stored. Inserting 6 stars here fails with CHECK constraint failed. That's the point: a constraint you set once beats checking every report for bad rows forever after. (SQLite only enforces REFERENCES after PRAGMA foreign_keys = ON;; most databases always do. ON DELETE CASCADE on a foreign key deletes the child rows too, and the default refuses to delete a row that's still referenced.)

Types differ by database. Common ones: INTEGER, NUMERIC(10, 2) or DECIMAL for money (exact, unlike REAL or FLOAT, which can round 0.1 + 0.2 to 0.30000000000000004), TEXT or VARCHAR(n), DATE, TIMESTAMP and BOOLEAN. SQLite is relaxed about types; most others are strict.

The main design rule is to store each fact once, called normalisation. If orders held the customer's city as well as their id, a customer who moves would need every old order fixed, and you'd find orders that disagree. Keep the city in customers and join to it. Warehouses sometimes copy facts on purpose ("denormalise") to make reports faster, but they do it knowingly, from a normalised source.

A view is a saved query with a name. It stores no data; querying it runs the query underneath. Good for a calculation everyone needs the same way:

CREATE VIEW order_totals AS
  SELECT i.order_id, SUM(i.qty * p.price) AS total
  FROM order_items i JOIN products p ON p.id = i.product_id
  GROUP BY i.order_id;

SELECT order_id, total FROM order_totals WHERE total > 80 ORDER BY total DESC;
Returns
order_id | total
---------+------
105      | 93.5
110      | 81.5
(2 rows)

Practice

Create a table wishlist with an id primary key, a customer_id and a product_id (both whole numbers that must be filled in), and make each customer-product pair unique. Insert the rows (1, 1, 8) and (2, 3, 8), then select how many rows the table has.

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

CREATE TABLE t (col TYPE rules, …)Make a table.
PRIMARY KEY, NOT NULL, UNIQUEOwn value; must be filled; no repeats.
CHECK (…), DEFAULT …A rule every row passes; a value when left out.
REFERENCES t(id)A foreign key (PRAGMA foreign_keys = ON in SQLite).
NUMERIC(10, 2)Exact decimals for money.
normalisationEach fact stored once.
CREATE VIEW v AS SELECT …A saved, named query.

The other AI and data engineering courses