Final challenge: a new student
After this: Add a student and his courses in transactions, recover from a failed step, and tidy up in the right order.
Gus, a new student, joins the school, takes two courses, gets a mark, tries to add two more courses, and finally leaves. This challenge follows him through five steps, and each step is scored on its own. You will count the rows a transaction adds, finish a transaction, predict an UPDATE, decide what to send after a failed statement, and put two DELETEs in the right order. Every step starts from where the one before it ended. You can try as many times as you like, and hints work as they do in the lessons.
Step 1 of 5Enrol Gus
Enrol Gus
The school starts with 10 enrolments, and nobody takes Music (course 5). After this transaction, how many enrolments are there, and how many students take Music?
BEGIN;INSERT INTO students (id, name, year, city)VALUES (7, 'Gus', 1, 'Hull');INSERT INTO enrolments (student_id, course_id)VALUES (7, 5), (7, 4);COMMIT;Keep both changes
Gus's row and his two enrolments must be kept together. Complete the last line of the transaction.
BEGIN;INSERT INTO students (id, name, year, city)VALUES (7, 'Gus', 1, 'Hull');INSERT INTO enrolments (student_id, course_id)VALUES (7, 5), (7, 4);_________ -- ← keep both changesMark Gus's Art
Art (course 4) had Ben with 90 and Dev with 76, and now Gus with no mark. What does the SELECT show after this UPDATE?
UPDATE enrolments SET mark = 88WHERE student_id = 7 AND course_id = 4;
SELECT student_id, mark FROM enrolmentsWHERE course_id = 4ORDER BY student_id;A failed statement
A second transaction enrols Gus in Maths (course 1) and then in course 9. There is no course 9, so the third statement fails with FOREIGN KEY constraint failed. What should the program send next, and where does that leave Gus?
BEGIN;INSERT INTO enrolments (student_id, course_id)VALUES (7, 1);INSERT INTO enrolments (student_id, course_id)VALUES (7, 9);Tidy up
Gus has left. These two statements remove him. Why must the enrolments go first?
DELETE FROM enrolments WHERE student_id = 7;DELETE FROM students WHERE id = 7;- Add a student and his enrolments in one transaction, update one mark, roll back a transaction whose second step failed, and delete rows in the order the foreign keys allow.