2

I'm trying to understand expections in postgresql. Maybe my problem is easy but not for me. Can someone tell me what is wrong with this query ? ERROR: syntax error at or near "EXCEPTION"

BEGIN;
select 1;
EXCEPTION 
    WHEN others THEN    
        RAISE INFO 'Caught';
END;
4
  • Remove the semicolon (;) after BEGIN. Commented Apr 1, 2019 at 19:41
  • ERROR: syntax error at or near "select" after remove semicolon after BEGIN Commented Apr 1, 2019 at 19:43
  • You do have this code fragment in a function, procedure or DO block? Commented Apr 1, 2019 at 19:45
  • No. I need to have exception block in one of those ? Commented Apr 1, 2019 at 19:47

1 Answer 1

3

If you want an anonymous block you'd have to use DO. You can't just start a block in the middle of nowhere.

DO
$$
BEGIN
  SELECT 1;
EXCEPTION WHEN others THEN    
  RAISE INFO 'Caught';
END;
$$
LANGUAGE PLpgSQL;
Sign up to request clarification or add additional context in comments.

2 Comments

I tried to run this as query on sqlfiddle.com but I have error Unterminated dollar quote started at position 3 in SQL DO $$ BEGIN SELECT 1. Expected terminating $$
@Sekru: That's an issue of the parser there and has nothing to do with Postgres. The error goes away if you select another (other than the semicolon) query terminator in the right dropdown. But it also seems like you cannot see emitted messages there, so you'd probably better get a local installation of Postgres for your tests.

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.