patternsqlModerate
Why doesn't INSERT AFTER Trigger add all results?
Viewed 0 times
afterwhytriggerinsertalldoesnresultsadd
Problem
I'm working on the exercises for db-class.org where we have to write a trigger that makes new students named 'Friendly' automatically like everyone else in their grade. That is, after the trigger runs, we should have ('Friendly', A) in the Likes table for every other Highschooler A in the same grade as 'Friendly'.
This is being done in sqlite on the following dataset. Now my trigger works, but it only adds one person that 'Friendly' likes rather than all of them (those with the same grade).
Here's my trigger:
I suspect there's something wrong with my INSERT query, because in isolation the SELECT returns all the IDs. So how do I make sure it inserts all the IDs with matching grades?
This is being done in sqlite on the following dataset. Now my trigger works, but it only adds one person that 'Friendly' likes rather than all of them (those with the same grade).
Here's my trigger:
CREATE Trigger Q1
After Insert on Highschooler
For Each Row
When New.Name = 'Friendly'
Begin
INSERT Into Likes Values (New.ID, (
SELECT Highschooler.ID FROM Highschooler
WHERE Highschooler.Grade = New.Grade));
End;I suspect there's something wrong with my INSERT query, because in isolation the SELECT returns all the IDs. So how do I make sure it inserts all the IDs with matching grades?
Solution
On most platforms your
What you are probably after is an
insert would throw an error if your subselect returns more than one row, rather than just insert the 'first' returned row (and 'first' is undefined without an order by clause).What you are probably after is an
insert like this:INSERT Into Likes
SELECT New.ID, ID
FROM Highschooler
WHERE Grade = New.Grade and ID<>New.ID;Code Snippets
INSERT Into Likes
SELECT New.ID, ID
FROM Highschooler
WHERE Grade = New.Grade and ID<>New.ID;Context
StackExchange Database Administrators Q#8045, answer score: 11
Revisions (0)
No revisions yet.