Lesson 9 of 10 · 10 min · 2 hands-on steps
Designing & Creating Tables
Pick columns, types and keys that keep your data correct.
CREATE TABLE
CREATE TABLE users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO users (email, name) VALUES ('ada@example.com', 'Ada');
SELECT * FROM users;Constraints protect your data
| Constraint | Meaning |
|---|---|
PRIMARY KEY |
unique id for each row |
NOT NULL |
a value is required |
UNIQUE |
no two rows can share this value (great for emails) |
DEFAULT |
value to use if none is given |
REFERENCES other(id) |
must point to a real row (a foreign key) |
Try breaking a rule. The database refuses:
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE);
INSERT INTO users (email) VALUES ('a@b.co');
INSERT INTO users (email) VALUES ('a@b.co');That error is a good thing. Constraints catch bugs that would otherwise silently corrupt your data.
Design rule: one fact, one place
If the same information appears in many rows (like an author's name on every book), move it into its own table and point to it with an id. This is called normalization, and it's the core idea of relational database design.
This site's own database follows these rules: users, sessions, memberships and progress are separate tables linked by
user_id.
🧪 Practice: 2 steps
0 / 2 doneStep 1 of 2 · A courses table
Create a table courses with:
idINTEGER PRIMARY KEYtitleTEXT, NOT NULLlessonsINTEGER
Insert two courses, ('SQL', 10) and ('Python', 12), then select title, lessons ordered by title.
CREATE TABLE courses ( id INTEGER PRIMARY KEY -- add the title and lessons columns (don't forget the commas) ); -- insert two courses, then select them
Output appears here. Press Run or Ctrl/⌘ + Enter.
Step 2 of 2 · Link two tables
Create authors(id INTEGER PRIMARY KEY, name TEXT) and books(id INTEGER PRIMARY KEY, title TEXT, author_id INTEGER REFERENCES authors(id)).
Insert author Ursula (id 1) with books Earthsea and The Dispossessed, then return each book title with its author name (as author), ordered by title.
-- create both tables, insert data, then join them
Output appears here. Press Run or Ctrl/⌘ + Enter.
✅ Check your understanding
What does a PRIMARY KEY guarantee?
Why store author_id in books instead of the author's name?
Create a free account to track your progress.