0

How to run a given select statement based on condition?

If a condition (which comes from table_A) is true then select from table_B otherwise from table_C. Tables have no common column.

Something like this

select case when table_A.flag=true then   
    (select * from table_B ) 
    else
    (select * from table_C ) 
    end
from table_A where ...

The above one will fail of course : more than one row returned by a subquery used as an expression

9
  • @Shmiel yes, updated the example Commented May 18, 2022 at 17:15
  • Did you try using an if statement? Commented May 18, 2022 at 17:20
  • Does this answer your question? PostgreSQL IF statement Commented May 18, 2022 at 17:20
  • @Shmiel sorry, forgot to mention it should be plain sql Commented May 18, 2022 at 17:58
  • This if statement is plain sql. It would work as follows if (select <column> from <table>) = <condition> then (select * from table) else (select * from other_table) Commented May 18, 2022 at 18:23

1 Answer 1

2

Since the columns are the same, you could use a UNION. Something like:

SELECT *
FROM Table_B
WHERE (SELECT flag FROM Table_A) = true
UNION ALL
SELECT *
FROM Table_C
WHERE (SELECT flag FROM Table_A) <> true

I'm assuming here that Table_A has only one row, but you could adjust the subquery in the WHERE conditions to get the flag however you need it.

The basic idea is that you set up the two conditions so that only one of them is true at a time (based on your flag). So, even though it is a UNION, only one part of the query will return results and you either end up with Table_B or Table_C.

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

Comments

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.