Skip to content
Lesson 9 of 10 · SQL for Beginners

Designing tables

Create tables with keys and constraints, and split data so each fact lives in one place.

20 min

Good table design stops bad data before it arrives. You create a table with CREATE TABLE, naming each column, its type and its rules:

sql7 lines
CREATE TABLE reviews (
  id        INTEGER PRIMARY KEY,
  book_id   INTEGER NOT NULL REFERENCES books(id),
  stars     INTEGER NOT NULL CHECK (stars BETWEEN 1 AND 5),
  comment   TEXT,
  posted    TEXT DEFAULT '2024-01-01'
);

SQLite is relaxed about types. The ones you will use: INTEGER, REAL (decimals), TEXT (including dates as '2024-03-15'), and BLOB. Other databases are stricter and have more (DATE, DECIMAL, BOOLEAN), but the idea is the same.

ConstraintMeaning
PRIMARY KEYuniquely identifies a row; no duplicates, never NULL
NOT NULLa value is required
UNIQUEno two rows share this value
DEFAULT xused when you do not give one
CHECK (...)a rule every row must satisfy
REFERENCES t(col)a foreign key: must match a row in another table

A foreign key stops an order pointing at a customer who does not exist. (In SQLite you switch that checking on with PRAGMA foreign_keys = ON; at the start of each connection.)

Do not store a list in one cell ('fiction, cooking'), and do not copy a customer's name into every order. When you repeat a fact, one edit is no longer enough and the copies drift apart. Instead:

  • One-to-many: put the foreign key on the "many" side (orders.customer_id).
  • Many-to-many: use a junction table. One order has many books, and one book is in many orders, so order_items(order_id, book_id, qty) links them.

Use a plain integer id the database fills in. Natural keys (an email, a name) change, and a changed key is painful to fix everywhere it was copied.

One-to-many relationships; order_items is the junction table that links orders and books.

Where to put the data

Customer name in every order row

Duplicated facts
the same name repeated many times
Risk
a rename must change every row
Fix
—

Best for store it once in customers, keep customer_id in orders

A "genres" cell holding "fiction, cooking"

Duplicated facts
several values in one cell
Risk
cannot filter or count cleanly
Fix
—

Best for a separate row per pair in a junction table

A total stored beside the lines it adds up

Duplicated facts
two sources of truth
Risk
they drift apart
Fix
—

Best for calculate the total with SUM when you need it

Exercise1 check
sql

Create a table reviews with: id (integer primary key), book_id (integer, required), stars (integer, required, between 1 and 5), comment (text). Insert two rows: book 1 with 5 stars, and book 2 with 3 stars (no comment). Then show book_id and stars ordered by id.

Tables you can query

  • books (id, title, author, genre, price, year, stock)
starter code7 lines
CREATE TABLE reviews (
  
);

INSERT INTO reviews (book_id, stars) VALUES (1, 5), (2, 3);

SELECT book_id, stars FROM reviews ORDER BY id;
Exercise1 check
sql

Create a wishlist table wishlist(customer_id, book_id, added) where the pair (customer_id, book_id) is the primary key and added defaults to the text 2024-05-01. Insert two rows for customer 1 (books 3 and 9) without giving added, then show every column ordered by book_id.

Tables you can query

  • books (id, title, author, genre, price, year, stock)
starter code7 lines
CREATE TABLE wishlist (
  
);

INSERT INTO wishlist (customer_id, book_id) VALUES (1, 3), (1, 9);

SELECT * FROM wishlist ORDER BY book_id;
Common misconception

“Storing "fiction, cooking" in one `genres` column is simple and fine.”

It saves a table, and the data reads naturally to a person.

What is actually true

You can no longer filter, count or join on a single genre cleanly: LIKE '%fiction%' also matches "non-fiction"-style names and the data can contain typos. A junction table gives one row per fact.

How to catch yourself

If you find yourself splitting text on commas, the design wants another table.

  • CREATE TABLE defines columns, types and rules; constraints (PRIMARY KEY, NOT NULL, UNIQUE, CHECK, DEFAULT) keep bad data out.
  • A foreign key (REFERENCES) ties a row to a row in another table.
  • Keep each fact in one place: one-to-many uses a foreign key, many-to-many uses a junction table.
  • Prefer a simple integer primary key over a name or email.
Check yourself

Design checks.

1Multiple choice

Which constraint makes a column required?

  • AUNIQUE
  • BNOT NULL
  • CDEFAULT
  • DCHECK
2Multiple choice

A student can take many courses and a course has many students. How do you store it?

  • AA "courses" column in students
  • BA junction table with student_id and course_id
  • CA "students" column in courses
  • DTwo copies of each table
3Multiple choice

Where does the foreign key go in a one-to-many relationship (one customer, many orders)?

  • AOn the customer row
  • BOn each order row
  • CIn a third table only
  • DNowhere
4Multiple choice

What does CHECK (stars BETWEEN 1 AND 5) do?

  • ARejects rows with stars outside 1 to 5
  • BSorts the table
  • CRounds the value
  • DCreates an index
5Select all that apply

Which are good reasons to avoid copying a customer's name into every order?

  • AA rename needs many edits
  • BCopies can drift apart
  • CIt saves no space at all but is required by SQL
  • DOne source of truth is easier to keep correct
For you · never graded

Pick something you track by hand (workouts, a reading list, a small business). Which tables would it need, and which columns link them?

Practise this lesson, not just read it

In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of SQL for Beginners is planned around your week. Free.