TalentJR

🗄️ SQL for beginners · Class 12 · Lesson 5 of 18 · Free

Data Design in SQL – Keys, Relationships and CREATE TABLE Constraints

⏱ About 35 minutes · ▶ run real SQL here — nothing to install · no sign-in

In this lesson you will

  • Create tables with a primary key and the right column types
  • Protect data with NOT NULL, UNIQUE, CHECK, DEFAULT and foreign keys
  • Model one-to-many and many-to-many relationships

The school library used one big notebook: book name, borrower name, class, date, all on one line. Then two students named Riya borrowed books, a title was spelt three ways, and nobody knew which copies were really out. Good table design stops these problems before they start.

What is a primary key in SQL?

A primary key is a column whose value is different for every row. It is how the database tells two rows apart, even when two students are both called Riya. A roll number or a library card number is a primary key in real life.

CREATE TABLE makes a new table: a name, then each column with its type. In SQLite, a column written INTEGER PRIMARY KEY fills itself with 1, 2, 3 … when you leave it out. In Lesson 3 you saw that PostgreSQL uses SERIAL and MySQL uses AUTO_INCREMENT for this.

Never use a name as a primary key. Names repeat and change; ids do not.

Try it: add a third member ('Riya', 11) and run. She gets her own id, so the two Riyas never mix up.

🗄️ SQL — you can edit this query
Result
Table members created.

2 rows inserted.

┌────┬───────┬───────┐
│ id │ name  │ class │
├────┼───────┼───────┤
│ 1  │ Riya  │ 12    │
│ 2  │ Kabir │ 12    │
└────┴───────┴───────┘
(2 rows)

Which constraints can you use in SQL CREATE TABLE?

A constraint is a rule the database checks on every INSERT and UPDATE. If a row breaks a rule, the database refuses it with an error, so bad data never gets in.

NOT NULL: a value is required. UNIQUE: no two rows may repeat it, like an email or a library book's code. CHECK (…): the value must pass a test, like copies >= 0. DEFAULT: the value used when you leave the column out.

Types: SQLite uses INTEGER, REAL (decimals), TEXT and BLOB, and it is relaxed about types. PostgreSQL and MySQL are stricter and also have VARCHAR(n), DATE and BOOLEAN. A table ending in STRICT makes SQLite check types too.

Try it: in the INSERT, change 3 to -1 for copies. The CHECK stops it.

🗄️ SQL — you can edit this query
Result
Table books created.

1 row inserted.

1 row inserted.

┌────┬───────────────┬────────┬────────────┐
│ id │ title         │ copies │ added_on   │
├────┼───────────────┼────────┼────────────┤
│ 1  │ Wings of Fire │ 3      │ 2026-06-01 │
│ 2  │ Malgudi Days  │ 1      │ 2026-06-01 │
└────┴───────────────┴────────┴────────────┘
(2 rows)

What is a foreign key in SQL and how does a one-to-many relationship work?

One member can borrow many books over time. So we keep loans in their own table, and each loan stores member_id, the id of a member. A column that points to a primary key in another table is a foreign key.

REFERENCES members(id) tells the database about the link. With it, the database refuses a loan for a member who does not exist.

Important: plain SQLite only checks foreign keys after PRAGMA foreign_keys = ON; it is off by default so that old programs keep working. The boxes on this page switch it on for you, and we still write the line so your code works anywhere. PostgreSQL and MySQL (InnoDB tables) always check them.

The members and books tables are already made for you in this box. Try it: change member_id 2 to 9 in the INSERT. You will see FOREIGN KEY constraint failed.

📋 Tables in this example: members, books — tap to see how they are made
PRAGMA foreign_keys = ON;
CREATE TABLE members (
    id    INTEGER PRIMARY KEY,
    name  TEXT NOT NULL,
    class INTEGER CHECK (class BETWEEN 1 AND 12)
);
CREATE TABLE books (
    id     INTEGER PRIMARY KEY,
    title  TEXT NOT NULL,
    copies INTEGER NOT NULL DEFAULT 1 CHECK (copies >= 0)
);
INSERT INTO members (name, class) VALUES ('Riya', 12), ('Kabir', 12), ('Meera', 11);
INSERT INTO books (title, copies) VALUES ('Wings of Fire', 3), ('Malgudi Days', 2), ('The Discovery of India', 1);
🗄️ SQL — you can edit this query
Result
Table loans created.

3 rows inserted.

┌───────┬───────────────┬────────────┐
│ name  │ title         │ taken_on   │
├───────┼───────────────┼────────────┤
│ Riya  │ Wings of Fire │ 2026-07-01 │
│ Riya  │ Malgudi Days  │ 2026-07-03 │
│ Kabir │ Wings of Fire │ 2026-07-04 │
└───────┴───────────────┴────────────┘
(3 rows)

How do you model a many-to-many relationship in SQL?

A student can join many clubs, and a club has many students. Neither table can hold the other's ids in one column. The answer is a third table, often called a junction or link table, with one row per pair.

PRIMARY KEY (student_id, club_id) is a composite key: the pair must be unique, so nobody joins the same club twice. Our practice database does the same: marks has PRIMARY KEY (student_id, subject_id).

Try it: add the pair (2, 1) so Kabir joins the Robotics club, then run again.

🗄️ SQL — you can edit this query
Result
Table students created.

Table clubs created.

Table club_members created.

3 rows inserted.

3 rows inserted.

5 rows inserted.

┌─────────┬──────────┐
│ student │ club     │
├─────────┼──────────┤
│ Kabir   │ Cricket  │
│ Meera   │ Cricket  │
│ Riya    │ Debate   │
│ Meera   │ Robotics │
│ Riya    │ Robotics │
└─────────┴──────────┘
(5 rows)

What happens to linked rows when you delete in SQL? (ON DELETE)

If a member leaves, what should happen to their loans? A foreign key can say. ON DELETE CASCADE deletes the linked rows too. ON DELETE SET NULL keeps them but clears the link. The default (no action) refuses the delete while linked rows exist.

Below, deleting Riya (member 1) also deletes her two loans, because of CASCADE. Kabir's loan stays.

Choose with care: you may not want old fee records to vanish when a student leaves. Try it: remove ON DELETE CASCADE and run again. Now the DELETE fails, because loans still point to Riya.

📋 Tables in this example: members, books — tap to see how they are made
PRAGMA foreign_keys = ON;
CREATE TABLE members (
    id    INTEGER PRIMARY KEY,
    name  TEXT NOT NULL,
    class INTEGER CHECK (class BETWEEN 1 AND 12)
);
CREATE TABLE books (
    id     INTEGER PRIMARY KEY,
    title  TEXT NOT NULL,
    copies INTEGER NOT NULL DEFAULT 1 CHECK (copies >= 0)
);
INSERT INTO members (name, class) VALUES ('Riya', 12), ('Kabir', 12), ('Meera', 11);
INSERT INTO books (title, copies) VALUES ('Wings of Fire', 3), ('Malgudi Days', 2), ('The Discovery of India', 1);
🗄️ SQL — you can edit this query
Result
Table loans created.

3 rows inserted.

1 row deleted.

┌────┬───────────┬─────────┐
│ id │ member_id │ book_id │
├────┼───────────┼─────────┤
│ 3  │ 2         │ 3       │
└────┴───────────┴─────────┘
(1 row)

🤔 Predict the output

Think like SQL: read the code and choose what it prints. You get the reason straight away.

Question 1. What does the SELECT return?

CREATE TABLE fines (
    id     INTEGER PRIMARY KEY,
    name   TEXT NOT NULL,
    amount INTEGER DEFAULT 0
);
INSERT INTO fines (name) VALUES ('Riya'), ('Aman');
SELECT id, amount FROM fines ORDER BY id;

Question 2. Riya (member 1) is deleted. What does the last SELECT return?

CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE loans (
    id        INTEGER PRIMARY KEY,
    member_id INTEGER REFERENCES members(id) ON DELETE SET NULL
);
INSERT INTO members VALUES (1, 'Riya'), (2, 'Kabir');
INSERT INTO loans (member_id) VALUES (1), (2);
DELETE FROM members WHERE id = 1;
SELECT member_id FROM loans ORDER BY id;

Question 3. email is UNIQUE. What does the SELECT return?

CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO users (email) VALUES (NULL), (NULL);
SELECT id, email FROM users ORDER BY id;

🧩 Your challenge

The school wants to record fee payments. Create a table fee_payments with: id (auto number), student_id (required, must point to students(id)), amount (required, must be more than 0), paid_on (required text date) and mode (required, default 'cash', only 'cash', 'upi' or 'card'). Insert (1, 4500, '2026-07-05') without a mode and (2, 4500, '2026-07-09', 'upi'). Then show the student's name, amount and mode, ordered by id. Expected: Riya Sharma | 4500 | cash Aman Verma | 4500 | upi

Expected result :
Table fee_payments created.

1 row inserted.

1 row inserted.

┌─────────────┬────────┬──────┐
│ name        │ amount │ mode │
├─────────────┼────────┼──────┤
│ Riya Sharma │ 4500   │ cash │
│ Aman Verma  │ 4500   │ upi  │
└─────────────┴────────┴──────┘
(2 rows)
📋 Tables in this example: students, subjects, teachers, marks, fees — tap to see how they are made
-- TalentJR practice school (made-up data for SQL lessons)
CREATE TABLE students (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  class   INTEGER NOT NULL,
  section TEXT NOT NULL,
  city    TEXT,
  joined  TEXT NOT NULL
);
INSERT INTO students VALUES
 (1, 'Riya Sharma', 12, 'A', 'Pune', '2019-06-10'),
 (2, 'Aman Verma', 12, 'A', 'Mumbai', '2020-06-15'),
 (3, 'Sara Khan', 12, 'B', 'Pune', '2019-06-10'),
 (4, 'Dev Patil', 11, 'A', 'Nagpur', '2021-06-14'),
 (5, 'Meera Iyer', 11, 'B', 'Chennai', '2021-06-14'),
 (6, 'Kabir Singh', 12, 'B', 'Delhi', '2022-07-01'),
 (7, 'Anaya Joshi', 11, 'A', 'Pune', '2023-06-12'),
 (8, 'Rohan Das', 12, 'A', NULL, '2023-06-12');
CREATE TABLE subjects (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL UNIQUE
);
INSERT INTO subjects VALUES (1, 'Maths'), (2, 'Physics'), (3, 'Chemistry'), (4, 'Computer Science'), (5, 'English');
CREATE TABLE teachers (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  subject_id INTEGER REFERENCES subjects(id)
);
INSERT INTO teachers VALUES (1, 'Mrs. Kulkarni', 1), (2, 'Mr. Rao', 2), (3, 'Ms. Fernandes', 4), (4, 'Mr. Gupta', 5), (5, 'Mrs. Nair', NULL);
CREATE TABLE marks (
  student_id INTEGER NOT NULL REFERENCES students(id),
  subject_id INTEGER NOT NULL REFERENCES subjects(id),
  marks      INTEGER NOT NULL CHECK (marks BETWEEN 0 AND 100),
  PRIMARY KEY (student_id, subject_id)
);
INSERT INTO marks VALUES
 (1,1,92),(1,2,88),(1,3,79),(1,4,95),(1,5,84),
 (2,1,75),(2,2,68),(2,3,72),(2,4,81),(2,5,90),
 (3,1,81),(3,2,77),(3,3,85),(3,4,70),(3,5,88),
 (4,1,64),(4,2,58),(4,4,88),(4,5,71),
 (5,1,95),(5,2,91),(5,3,89),(5,4,93),(5,5,86),
 (6,1,55),(6,2,62),(6,3,49),(6,5,67),
 (7,1,73),(7,4,99),(7,5,80);
CREATE TABLE fees (
  student_id INTEGER NOT NULL REFERENCES students(id),
  month      TEXT NOT NULL,
  amount     INTEGER NOT NULL,
  paid       INTEGER NOT NULL DEFAULT 0
);
INSERT INTO fees VALUES
 (1,'2026-06',4500,1),(1,'2026-07',4500,1),(2,'2026-06',4500,1),(2,'2026-07',4500,0),
 (3,'2026-06',4500,1),(4,'2026-06',4000,1),(4,'2026-07',4000,0),(5,'2026-06',4000,1),
 (6,'2026-06',4500,0),(7,'2026-06',4000,1),(8,'2026-06',4500,1);
🗄️ SQL — you can edit this query

⚠️ Common mistakes (and how to fix them)

❌ Wrong

INSERT INTO members (id, name) VALUES (1, 'Riya');
INSERT INTO members (id, name) VALUES (1, 'Riya');

Error in statement 2 (INSERT): UNIQUE constraint failed: members.id

✅ Right

INSERT INTO members (name) VALUES ('Riya');
INSERT INTO members (name) VALUES ('Riya');

Typing the id yourself makes it easy to repeat one. Leave the id out and let INTEGER PRIMARY KEY number the rows.

❌ Wrong

INSERT INTO marks (student_id, subject_id, marks) VALUES (8, 1, 105);

Error in statement 1 (INSERT): CHECK constraint failed: marks BETWEEN 0 AND 100

✅ Right

INSERT INTO marks (student_id, subject_id, marks) VALUES (8, 1, 85);

The marks table has CHECK (marks BETWEEN 0 AND 100). The database protects the data even if the app forgets to check.

❌ Wrong

CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT, subjects TEXT);
INSERT INTO students (name, subjects) VALUES ('Riya', 'Maths, Physics'), ('Kabir', 'Physics');
SELECT name FROM students WHERE subjects = 'Physics';

Runs, but gives the wrong result: Table students created. 2 rows inserted. ┌───────┐ │ name │ ├───────┤ │ Kabir │

✅ Right

CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE student_subjects (student_id INTEGER, subject TEXT, PRIMARY KEY (student_id, subject));
INSERT INTO students (name) VALUES ('Riya'), ('Kabir');
INSERT INTO student_subjects VALUES (1, 'Maths'), (1, 'Physics'), (2, 'Physics');
SELECT s.name FROM students AS s JOIN student_subjects AS ss ON ss.student_id = s.id
WHERE ss.subject = 'Physics' ORDER BY s.name;

A list squeezed into one column ('Maths, Physics') cannot be searched or checked properly, so Riya is missed. Put one value per row in a separate table.

📌 Remember

  • A primary key gives every row its own id; INTEGER PRIMARY KEY numbers rows in SQLite.
  • NOT NULL, UNIQUE, CHECK and DEFAULT are rules the database checks on every change.
  • A foreign key (REFERENCES) links a row to a row in another table: one-to-many.
  • Many-to-many needs a link table with a composite key, like marks(student_id, subject_id).
  • Plain SQLite checks foreign keys only after PRAGMA foreign_keys = ON (this page turns it on for you).
  • Store one value per column; never squeeze lists into one text column.

Finished the quiz and the challenge?

Questions students ask

What is the difference between a primary key and a foreign key?

A primary key identifies each row of its own table. A foreign key is a column that stores another table's primary key, to link the two rows. loans.member_id is a foreign key that points to members.id.

Can a table have two primary keys?

A table has only one primary key, but that key can be made of two or more columns, like PRIMARY KEY (student_id, subject_id). For other columns that must be unique, use UNIQUE.

Why are foreign keys not working in SQLite?

Plain SQLite turns foreign key checks off by default. Run PRAGMA foreign_keys = ON; at the start of each connection, and the database will refuse rows that point to nothing.

Should I use VARCHAR or TEXT?

In SQLite and PostgreSQL, TEXT is fine for most text. VARCHAR(n) adds a length limit, which PostgreSQL and MySQL enforce. SQLite accepts VARCHAR(n) but does not enforce the length.