4

I need to create a data patching script and I'd like to rollback the transaction when some condition occurs.

I could do something like this in the end of the script:

select t.id / 0
from some_table t
where t.state = 'undersirable state'

but I'd rather have a more appropriate error message than "division by zero".

Is there a generic function for generating errors in PostgreSQL? I'd like to do it without PL/SQL, if possible.

3
  • 1
    "Is there a generic function for generating errors in PostgreSQL? I'd like to do it without PL/SQL, if possible." No there isn't anny for plain queries like these.. Commented Jun 14, 2019 at 9:22
  • 2
    "I'd like to do it without PL/SQL" - How come? If you just want to avoid creating a function, you can run it from a DO block. Commented Jun 14, 2019 at 9:35
  • @NickBarnes within a script, like the OP here was writing, yeah, that's a valid approach. I've still sometimes specifically wanted an expression that throws an error, though, for use as e.g. the default value of a CASE expression used within a SELECT or UPDATE. Commented Apr 18, 2021 at 9:01

1 Answer 1

7

Write a little function that raises the error for you and use that in your SELECT statement.

CREATE FUNCTION raise_error() RETURNS integer
   LANGUAGE plpgsql AS
$$BEGIN
   RAISE EXCEPTION /* whatever you want */;
   RETURN 42;
END;$$;
Sign up to request clarification or add additional context in comments.

2 Comments

That is brilliant! It is so obvious solution, yet I did not find it from any other place.

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.