Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise an error with PostgreSQL select statement?

Tags:

sql

postgresql

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.

like image 403
Aivar Avatar asked Sep 13 '25 23:09

Aivar


1 Answers

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;$$;
like image 148
Laurenz Albe Avatar answered Sep 16 '25 16:09

Laurenz Albe