简体   繁体   中英

When are table constraints checked in SQL inserts?

Let's say I have a trigger that should prevent something from being inserted in a table if a given condition isn't met. This means I probably should use BEFORE INSERT . Is this correct?

But if I use BEFORE INSERT , integrity constraints will not have been checked when I'm running the function on the trigger. So they might violate constraints (like not null constraints). The major problem with this is that I might try to do operations with data that isn't valid.

Is there a way to force the constraints to be checked, and then run the trigger, without actually inserting things into the table first?

It's unclear what you mean with the danger of trying operations with data that isn't valid.

If you get an exception in a BEFORE trigger because you are performing an operation there (say, a division by zero that would have been ruled out by a constraint), then the trigger and the whole INSERT will be aborted, quite as much as if the constraint would have thrown the exception later. So there's nothing to worry about.

On the other hand, if you want the constraints to be checked before you do your checks, just perform your checks in an AFTER trigger. Throwing an exception there will abort the insert just as well.

If both work, go for the BEFORE trigger. If you throw the exception before the row has been inserted, you are sure not to generate a dead tuple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM