TalentJR

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

SQL Triggers – Make the Database React to Changes Automatically

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

In this lesson you will

  • Create AFTER and BEFORE triggers with CREATE TRIGGER
  • Use OLD and NEW to read a row before and after a change
  • Keep counts in sync and block bad data with RAISE

A teacher changes a student's marks from 64 to 84. Was it a fair correction, or a mistake? The principal wants a record of every marks change, but nobody will remember to write it by hand. A trigger writes that record by itself, every single time.

What is a trigger in SQL?

A trigger is SQL that the database runs by itself when a row in a table is inserted, updated or deleted. You never call it. The change "fires" it, like a doorbell.

Below, marks_audit fires AFTER UPDATE of the marks column. It copies the old and new marks into marks_log. OLD is the row before the change; NEW is the row after.

In SQLite the trigger runs once for each changed row. Try it: change WHERE student_id = 4 to WHERE subject_id = 4 and run again. Six rows change, so six log lines appear.

📋 Tables in this example: students, subjects, teachers, marks, fees, marks_log — 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);
CREATE TABLE marks_log (
  student_id INTEGER,
  subject_id INTEGER,
  old_marks  INTEGER,
  new_marks  INTEGER
);
🗄️ SQL — you can edit this query
Result
Trigger marks_audit created.

1 row updated.

┌────────────┬────────────┬───────────┬───────────┐
│ student_id │ subject_id │ old_marks │ new_marks │
├────────────┼────────────┼───────────┼───────────┤
│ 4          │ 1          │ 64        │ 84        │
└────────────┴────────────┴───────────┴───────────┘
(1 row)

How do OLD and NEW work in SQLite triggers?

An INSERT has only NEW (there was no old row). A DELETE has only OLD (there is no new row). An UPDATE has both.

This trigger saves a deleted mark before it disappears, so nothing is lost without a trace. A WHEN condition can also limit when a trigger fires: here, only marks of 90 or more are logged.

Try it: change the WHEN line to WHEN OLD.marks >= 70 and run again.

📋 Tables in this example: students, subjects, teachers, marks, fees, marks_log — 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);
CREATE TABLE marks_log (
  student_id INTEGER,
  subject_id INTEGER,
  old_marks  INTEGER,
  new_marks  INTEGER
);
🗄️ SQL — you can edit this query
Result
Trigger marks_deleted created.

3 rows deleted.

┌────────────┬────────────┬───────────┬───────────┐
│ student_id │ subject_id │ old_marks │ new_marks │
├────────────┼────────────┼───────────┼───────────┤
│ 7          │ 4          │ 99        │ NULL      │
└────────────┴────────────┴───────────┴───────────┘
(1 row)

How do I keep a count in sync with a SQL trigger?

The school library keeps copies_available for each book. When a book is issued, it must go down by 1. When it is returned, up by 1. Forget once, and the count is wrong for ever.

Two triggers do it for every app that touches the issues table. The WHERE id = NEW.book_id part makes sure only the right book changes.

Try it: issue book 2 to student 3 as well and run again. Book 2 had 1 copy; the CHECK (copies_available >= 0) will stop a second issue.

📋 Tables in this example: students, subjects, teachers, marks, fees, books, issues — 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);
CREATE TABLE books (
  id               INTEGER PRIMARY KEY,
  title            TEXT NOT NULL,
  copies_available INTEGER NOT NULL CHECK (copies_available >= 0)
);
INSERT INTO books VALUES (1, 'Physics Part 1', 3), (2, 'Organic Chemistry Basics', 1), (3, 'Python for Beginners', 2);
CREATE TABLE issues (
  id         INTEGER PRIMARY KEY,
  book_id    INTEGER NOT NULL REFERENCES books(id),
  student_id INTEGER NOT NULL REFERENCES students(id),
  returned   INTEGER NOT NULL DEFAULT 0
);
🗄️ SQL — you can edit this query
Result
Trigger book_issued created.

Trigger book_returned created.

1 row inserted.

1 row inserted.

1 row updated.

┌──────────────────────────┬──────────────────┐
│ title                    │ copies_available │
├──────────────────────────┼──────────────────┤
│ Physics Part 1           │ 3                │
│ Organic Chemistry Basics │ 0                │
│ Python for Beginners     │ 2                │
└──────────────────────────┴──────────────────┘
(3 rows)

💡 Each statement in a trigger body ends with ; and the whole trigger ends with END;

How can a trigger block bad data in SQLite?

A BEFORE trigger runs before the change is made, so it can stop it. SELECT RAISE(ABORT, 'message') cancels the statement and shows your message as the error.

Library rule: a student may hold at most 2 books at a time. A CHECK constraint (Lesson 5) can only look at one row. A trigger can look at other rows, so it can count the books a student already has.

Try it: add a third line INSERT INTO issues (book_id, student_id) VALUES (3, 1); and run again. You will see the rule's message, and the third book is not issued.

📋 Tables in this example: students, subjects, teachers, marks, fees, books, issues — 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);
CREATE TABLE books (
  id               INTEGER PRIMARY KEY,
  title            TEXT NOT NULL,
  copies_available INTEGER NOT NULL CHECK (copies_available >= 0)
);
INSERT INTO books VALUES (1, 'Physics Part 1', 3), (2, 'Organic Chemistry Basics', 1), (3, 'Python for Beginners', 2);
CREATE TABLE issues (
  id         INTEGER PRIMARY KEY,
  book_id    INTEGER NOT NULL REFERENCES books(id),
  student_id INTEGER NOT NULL REFERENCES students(id),
  returned   INTEGER NOT NULL DEFAULT 0
);
🗄️ SQL — you can edit this query
Result
Trigger max_two_books created.

1 row inserted.

1 row inserted.

┌─────────┬────────────┐
│ book_id │ student_id │
├─────────┼────────────┤
│ 1       │ 1          │
│ 2       │ 1          │
└─────────┴────────────┘
(2 rows)

What is an INSTEAD OF trigger on a view?

In Lesson 10, SQLite refused INSERT into a view. An INSTEAD OF trigger fixes that. It says: instead of inserting into the view, run this SQL on the real table.

Here the office uses a simple view of Class 11. The trigger fills in the class number and the joining date, so the office types only the id, name and section.

The result says "0 rows inserted": nothing went into the view itself. The trigger did the real insert into students, as the last query shows. Try it: insert another student with id 10 into class11_list and run again.

📋 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);
CREATE VIEW class11_list AS SELECT id, name, section FROM students WHERE class = 11;
🗄️ SQL — you can edit this query
Result
Trigger class11_add created.

0 rows inserted.

┌────┬─────────────┬─────────┐
│ id │ name        │ section │
├────┼─────────────┼─────────┤
│ 4  │ Dev Patil   │ A       │
│ 5  │ Meera Iyer  │ B       │
│ 7  │ Anaya Joshi │ A       │
│ 9  │ Isha Rao    │ B       │
└────┴─────────────┴─────────┘
(4 rows)

How are triggers written in PostgreSQL and MySQL?

The idea is the same everywhere; the syntax differs. MySQL writes CREATE TRIGGER … AFTER UPDATE ON marks FOR EACH ROW and then the statement, much like SQLite.

PostgreSQL splits it in two. First a function in its PL/pgSQL language does the work. Then CREATE TRIGGER links the function to the table. NOW() stores the time of the change.

📄 Example to read — PostgreSQL syntax — shown, not run here
CREATE FUNCTION log_marks_change() RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO marks_log (student_id, subject_id, old_marks, new_marks, changed_at)
    VALUES (NEW.student_id, NEW.subject_id, OLD.marks, NEW.marks, NOW());
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER marks_audit
AFTER UPDATE OF marks ON marks
FOR EACH ROW
EXECUTE FUNCTION log_marks_change();

🤔 Predict the output

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

Question 1. Book 1 starts with 3 copies. What is left?

📋 The tables (tap to see them)
-- 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);
CREATE TABLE books (
  id               INTEGER PRIMARY KEY,
  title            TEXT NOT NULL,
  copies_available INTEGER NOT NULL CHECK (copies_available >= 0)
);
INSERT INTO books VALUES (1, 'Physics Part 1', 3), (2, 'Organic Chemistry Basics', 1), (3, 'Python for Beginners', 2);
CREATE TABLE issues (
  id         INTEGER PRIMARY KEY,
  book_id    INTEGER NOT NULL REFERENCES books(id),
  student_id INTEGER NOT NULL REFERENCES students(id),
  returned   INTEGER NOT NULL DEFAULT 0
);

CREATE TRIGGER book_issued
AFTER INSERT ON issues
BEGIN
    UPDATE books SET copies_available = copies_available - 1
    WHERE id = NEW.book_id;
END;

CREATE TRIGGER book_returned
AFTER UPDATE OF returned ON issues
WHEN OLD.returned = 0 AND NEW.returned = 1
BEGIN
    UPDATE books SET copies_available = copies_available + 1
    WHERE id = NEW.book_id;
END;
INSERT INTO issues (book_id, student_id) VALUES (1, 2);
INSERT INTO issues (book_id, student_id) VALUES (1, 4);

SELECT copies_available FROM books WHERE id = 1;

Question 2. The trigger logs only drops in marks. Riya's 5 marks each go up by 2. How many log rows?

📋 The tables (tap to see them)
-- 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);
CREATE TABLE marks_log (
  student_id INTEGER,
  subject_id INTEGER,
  old_marks  INTEGER,
  new_marks  INTEGER
);
CREATE TRIGGER marks_drop AFTER UPDATE OF marks ON marks
WHEN NEW.marks < OLD.marks
BEGIN
  INSERT INTO marks_log VALUES (NEW.student_id, NEW.subject_id, OLD.marks, NEW.marks);
END;
UPDATE marks SET marks = marks + 2 WHERE student_id = 1;

SELECT COUNT(*) FROM marks_log;

Question 3. Book 3 starts with 2 copies. What does the query return?

📋 The tables (tap to see them)
-- 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);
CREATE TABLE books (
  id               INTEGER PRIMARY KEY,
  title            TEXT NOT NULL,
  copies_available INTEGER NOT NULL CHECK (copies_available >= 0)
);
INSERT INTO books VALUES (1, 'Physics Part 1', 3), (2, 'Organic Chemistry Basics', 1), (3, 'Python for Beginners', 2);
CREATE TABLE issues (
  id         INTEGER PRIMARY KEY,
  book_id    INTEGER NOT NULL REFERENCES books(id),
  student_id INTEGER NOT NULL REFERENCES students(id),
  returned   INTEGER NOT NULL DEFAULT 0
);

CREATE TRIGGER book_issued
AFTER INSERT ON issues
BEGIN
    UPDATE books SET copies_available = copies_available - 1
    WHERE id = NEW.book_id;
END;

CREATE TRIGGER book_returned
AFTER UPDATE OF returned ON issues
WHEN OLD.returned = 0 AND NEW.returned = 1
BEGIN
    UPDATE books SET copies_available = copies_available + 1
    WHERE id = NEW.book_id;
END;
DROP TRIGGER book_issued;

INSERT INTO issues (book_id, student_id) VALUES (3, 6);

SELECT copies_available FROM books WHERE id = 3;

🧩 Your challenge

The accounts office wants a fee_log. Create a trigger fee_paid_log that runs AFTER UPDATE OF paid ON fees and writes student_id, month, OLD.paid and NEW.paid into fee_log. Then mark Aman's (2) July fee and Kabir's (6) June fee as paid, and list fee_log ordered by student_id. Expected: (2, 2026-07, 0, 1) and (6, 2026-06, 0, 1).

Expected result :
Trigger fee_paid_log created.

1 row updated.

1 row updated.

┌────────────┬─────────┬──────────┬──────────┐
│ student_id │ month   │ old_paid │ new_paid │
├────────────┼─────────┼──────────┼──────────┤
│ 2          │ 2026-07 │ 0        │ 1        │
│ 6          │ 2026-06 │ 0        │ 1        │
└────────────┴─────────┴──────────┴──────────┘
(2 rows)
📋 Tables in this example: students, subjects, teachers, marks, fees, fee_log — 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);
CREATE TABLE fee_log (student_id INTEGER, month TEXT, old_paid INTEGER, new_paid INTEGER);
🗄️ SQL — you can edit this query

⚠️ Common mistakes (and how to fix them)

❌ Wrong

CREATE TRIGGER marks_deleted AFTER DELETE ON marks
BEGIN
    INSERT INTO marks_log VALUES (NEW.student_id, NEW.subject_id, NEW.marks, NULL);
END;

DELETE FROM marks WHERE student_id = 7 AND subject_id = 1;

Error: no such column: NEW.student_id

✅ Right

CREATE TRIGGER marks_deleted AFTER DELETE ON marks
BEGIN
    INSERT INTO marks_log VALUES (OLD.student_id, OLD.subject_id, OLD.marks, NULL);
END;

DELETE FROM marks WHERE student_id = 7 AND subject_id = 1;
SELECT * FROM marks_log;

After a DELETE there is no new row, so NEW does not exist. Use OLD in DELETE triggers.

❌ Wrong

CREATE TRIGGER book_issued AFTER INSERT ON issues
BEGIN
    UPDATE books SET copies_available = copies_available - 1;
END;

INSERT INTO issues (book_id, student_id) VALUES (3, 1);
SELECT title, copies_available FROM books ORDER BY id;

Runs, but gives the wrong result: Trigger book_issued created. 1 row inserted. ┌──────────────────────────┬──────────────────┐ │ title │ copies_available │ ├──────────────────────────┼──────────────────┤ │ Physics Part 1 │ 2 │

✅ Right

CREATE TRIGGER book_issued AFTER INSERT ON issues
BEGIN
    UPDATE books SET copies_available = copies_available - 1
    WHERE id = NEW.book_id;
END;

INSERT INTO issues (book_id, student_id) VALUES (3, 1);
SELECT title, copies_available FROM books ORDER BY id;

Without WHERE id = NEW.book_id, the UPDATE inside the trigger changes every book. Always tie the trigger's work to the changed row.

❌ Wrong

CREATE TRIGGER marks_audit AFTER UPDATE OF marks ON marks
BEGIN
    INSERT INTO marks_log VALUES (NEW.student_id, NEW.subject_id, OLD.marks, NEW.marks)
END;

Error: near "END": syntax error

✅ Right

CREATE TRIGGER marks_audit AFTER UPDATE OF marks ON marks
BEGIN
    INSERT INTO marks_log VALUES (NEW.student_id, NEW.subject_id, OLD.marks, NEW.marks);
END;

Every statement inside BEGIN … END needs its own semicolon, even the last one.

📌 Remember

  • A trigger is SQL that runs by itself when rows are inserted, updated or deleted.
  • AFTER triggers do follow-up work; BEFORE triggers can stop a change with RAISE(ABORT, '…').
  • NEW is the row after the change, OLD the row before; INSERT has only NEW, DELETE only OLD.
  • WHEN limits when a trigger fires; WHERE … = NEW.id keeps its work on the right rows.
  • INSTEAD OF triggers make views writable in SQLite; DROP TRIGGER removes a trigger.

Finished the quiz and the challenge?

Questions students ask

What is the difference between a trigger and a stored procedure?

You run a stored procedure yourself with CALL. A trigger runs by itself when a table changes. SQLite has triggers but no stored procedures (Lesson 13).

What is the difference between BEFORE and AFTER triggers?

A BEFORE trigger runs before the row changes, so it is good for checks that may cancel the change. An AFTER trigger runs once the change is done, so it is good for logs and keeping other tables in step.

Can triggers slow down a database?

Yes, a little: every matching change also runs the trigger's SQL. Keep trigger bodies short. Too many hidden triggers also make bugs hard to find, so write down what each one does.

Does a trigger's work get undone if the change is rolled back?

Yes. A trigger runs inside the same transaction as the statement that fired it (Lesson 12). If that is rolled back, the trigger's changes are rolled back too.