Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does SQL standard specify the order of constraint validation and trigger firing?

I'm curious if I can rely on any particular order of validating NOT NULL, FOREIGN KEY, UNIQUE, CHECK constraints and BEFORE triggers.

From experience I know that MySQL first checks NOT NULL, then launches BEFORE trigger, and then checks UNIQUE constraints. Oracle checks NOT NULL after the BEFORE trigger ( I believe SQLServer does the same, but don't remember). Does the standard say anything about the order or it's completely up to DB vendor?

like image 321
a1ex07 Avatar asked Nov 21 '11 23:11

a1ex07


1 Answers

That particular behavior seems to be a bug in MySQL, and it only affects BEFORE INSERT triggers, while BEFORE UPDATE triggers behave correctly.

The standard (as linked in question comments) certainly doesn't spell it out explicitly, but it's definitely implied:

For each state change SCi,j in TECi, the BEFORE triggers activated by SCi,j are executed before any of their triggering events take effect. When those triggering events have taken effect, any AFTER triggers activated by the state changes of TECi are executed.

A NOT NULL error should be part of an INSERT or UPDATE (i.e. the triggering event). The standard should not need to specify this. There is absolutely no point to pre-emptively checking constraints on a set of changes which is not final because your BEFORE trigger is capable of both resolving errors and introducing new ones.

SUMMARY: It really isn't up to the DB vendor because checking constraints after a before trigger is always necessary.

like image 152
Kevin Stricker Avatar answered Sep 22 '22 22:09

Kevin Stricker