0

It's a disaster that I, coming from MySQL and T-SQL, cannot figure out from documentation (0 real examples) and stackoverflow (0 real examples) how to deal with the most basic variable management in PostgreSQL.

Code below causes an error ERROR: duplicate declaration...

declare invalidThirdUser boolean := 'false';
    
invalidThirdUser = (select 'true' where NEW.sender_id not in(
    select user1_id from thread where id = NEW.thread_id
    union all
    select user2_id from thread where id = NEW.thread_id
));

I tried

invalidThirdUser = (select...

invalidThirdUser := (select...

set invalidThirdUser = (select...

select invalidThirdUser = (select...

How painful is assigning a new value to variable in postgres? Thanks.

3
  • Edit the question and provide a minimal reproducible example, in this case the CREATE statements of the table (paste the text, don't use images) and a DO block where you declare and assign to the variable (dito). Instead of the DO block a simple function definition would do to but is more complicated. Commented Mar 25, 2021 at 0:21
  • And by the way, the literals for Booleans are simply true and false, there's no need for the ' which makes them actually string literals that get -- unnecessarily -- implicitly casted. Commented Mar 25, 2021 at 0:23
  • And you can omit the subquery. Just new.sender_id NOT IN (...) is an expression that already evaluates to a Boolean value. Commented Mar 25, 2021 at 0:27

1 Answer 1

1

This is very simple example, how to deal with the most basic variable management in PostgreSQL:

do $$
declare
    invalidThirdUser boolean DEFAULT FALSE;
begin
    RAISE NOTICE '%', invalidThirdUser; -- check variable's current value
    
    invalidThirdUser := TRUE; -- set new value  
    RAISE NOTICE '%', invalidThirdUser; -- check variable's current value
    
    SELECT FALSE INTO invalidThirdUser; -- set new value  again, but using SELECT..INTO way
    RAISE NOTICE '%', invalidThirdUser; -- check variable's current value

end; $$ language plpgsql
Sign up to request clarification or add additional context in comments.

1 Comment

Why it's impossible to declare variable inside begin...end block? It's like to be forced to declare variables outside function block in programming. Why it's impossible to select a variable to output is as single result set used by 3rd party applications?

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.