5

I want to perform some business validation of the data being inserted in a table and I need to check data in another table when doing so. The way to this seems to be using a BEFORE INSERT FOR EACH ROW TRIGGER in PostgreSQL and from the function it calls I can return NULL if the new data fails validation to prevent it being inserted.

Is there any way I can return an error message describing the validation error as well?

1
  • In addition to @mu's answer, consider this if you want a context for your own exceptions. Commented Jun 7, 2012 at 22:05

1 Answer 1

12

Use raise for exceptions:

39.8. Errors and Messages

Use the RAISE statement to report messages and raise errors.
[...]
EXCEPTION raises an error (which normally aborts the current transaction);

So you can say things like this in your trigger:

raise exception 'Say something useful about %', some_variable;

That will abort the trigger and (usually) the current transaction. The message that you raise should make its way back to the client application.

Sign up to request clarification or add additional context in comments.

1 Comment

careful, you can't use NOTIFY in a trigger if there's an exception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.