I have table "Candidates" with id (primary key) and application_counter
and table "Applications" with foreign key (candidate_id). I want application_counter to be modified each time Application is added or removed (or modified by changing candidate_id).
All I can do is to write:
CREATE TRIGGER myTrigger AFTER INSERT OR DELETE OR UPDATE
ON "Applications" FOR EACH ROW
EXECUTE PROCEDURE funcname ( arguments )
And the question is How can I write this trigger?
Synopsis from page http://www.postgresql.org/docs/8.1/interactive/sql-createtrigger.html
CREATE TRIGGER name { BEFORE | AFTER } { event [ OR ... ] }
ON table [ FOR [ EACH ] { ROW | STATEMENT } ]
EXECUTE PROCEDURE funcname ( arguments )
I’d use a view,
INNER JOINthe two tables, and count the rows in theapplicationstable. (SeeCOUNT().) Triggers can be disabled; that view will always give you the right answer.(Later . . .)
I understand you want to limit a candidate’s rows in the table “applications” to 3 or less. In that case, I think it’s best to use a
CHECK()constraint on “applications” rather than the combination of a trigger on “applications” and aCHECK()constraint on “candidates”.To do that in PostgreSQL, you have to use a function, and call the function from the
CHECK(). (As far as I know. You still can’t execute arbitrarySELECTstatements inCHECK()constraints, right?) So, you’d create this function,and then you’d add a CHECK() constraint to the table ‘applications’.
“< 3” because the
CHECK()constraint is evaluated before adding a row. It’s probably worth testing to see how this behaves with deferred constraints. If I have time later, I’ll do that.