Syntax error on declaring a variable inside a transaction I want to create a variable inside this transaction but I'm getting


  ERROR: syntax error at or near "DECLARE" LINE 4: DECLARE new_id INTEGER;.


The variable needs to hold the value of the id of the newly created message.
This seems to be the cleanest and race condition resistant way of doing so, but I don't know how to correctly declare the variable.

BEGIN TRANSACTION;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

DECLARE new_id INTEGER;
INSERT INTO messages (author) VALUES ($author) RETURNING id INTO new_id;
-- Other statements..

COMMIT;
Try using a declare block before the main block:

DECLARE
  -- declarations go here
BEGIN
  -- commands go here
END;


If you need this as an anonymous block (not in any function, etc.) also read about DO.