Home > Back-end >  Postgresql select from based on condition
Postgresql select from based on condition

Time:05-19

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

CodePudding user response:

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.

  • Related