PostgreSQL conditional expression

I need to implement a conditional statement SELECT

based on the result of another statement. I don't want to create a function for this purpose, but just using a conditional SELECT

.

My unfortunate approach looks like this:

DO
$do$
BEGIN
IF SELECT count(*) FROM table1 < 1 THEN
   SELECT * FROM table2;
   RETURN QUERY;

ELSE 
   SELECT * FROM table3;
   RETURN QUERY;
END IF;
END
$do$

      

I could achieve the same result by checking the results of my query in PHP and based on that, execute another query, but I am wondering if this is only possible in PostgreSQL.

+3


source to share


2 answers


Try the following:



with c as (select count(*) cnt from table1)
select table2.* from table2, c where c.cnt < 1
union all
select table3.* from table3, c where c.cnt >= 1

      

+2


source


If table2 and table3 are union compatible, you can use one SELECT:



SELECT * FROM table2 WHERE NOT EXISTS(SELECT * FROM table1)
UNION
SELECT * FROM table3 WHERE EXISTS(SELECT * FROM table1);

      

+2


source







All Articles