skip to Main Content

I am transferring a project from SQL to PG.
There is such a query in SQL:

if(condition)
begin
select * from users;
end

The conversion to PG should be with as few changes as possible to maintain the structure of the project
I try to do so:

do $$
begin
if(condition)
then
create table v_output as 
select * from users;
end if;
end$$;
select * from v_output;
drop table v_output;

In order to get an output, I insert into a temporary table, then select from it
What happens if the condition is FALSE
I get relation "v_output" does not exist
It makes sense that if the condition is negative, the table is never created
Is there a way to solve this?

2

Answers


  1. A guess: you don’t need pl/pgsql and that temporary table at all. Just do

    select *
    from users
    where condition;
    
    Login or Signup to reply.
  2. It makes sense that if the condition is negative, the table is never created.

    No, you are mistaken here. It makes sense that the table is never filled if the condition is false. However the table must exist regardless of the condition because you later select from it regardless of the condition.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search