1

On PostgreSQL, I am trying to loop through alternative query results.

I have this solution working:

FOR target
IN query
LOOP
  statements
END LOOP;

But I want to do something like this:

FOR target
IN (IF condition_1
    THEN query_1
    ELSE query_2
    END IF)
LOOP
  statements
END LOOP;

However I cannot make it to work. I have also tried this version but it's also not working:

FOR target
IN (CASE
      WHEN condition_1 THEN query_1
      ELSE query_2
    END)
LOOP
  statements
END LOOP;

Is there any way of implementing this behavior in PostgreSQL?

Thanks!

1 Answer 1

1

You could use:

FOR target
IN (SELECT ... FROM ... WHERE     condition1
    UNION ALL
    SELECT ... FROM ... WHERE NOT condition1)
LOOP
  statements
END LOOP;

Queries: query1 and query2 are combined with UNION ALL but condition will pass only single part depending of value.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the tip Lukasz, I will try your suggestion!
I could make it to work. Once again thank you so much Lukasz!
@InêsSantos Glad to hear that. How does accepting an answer work?
I'm sorry @Luckasz, it was my first question here and I didn't know about accepting answers. I have accepted it now :)

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.