Qvery
Qvery

Reputation: 23

Using CASE in PostgreSQL to SELECT different FROMs

I'll try to create a query where the result can be from two different tables depending on the size of the first table. Is something comparable even possible?

SELECT 
    CASE WHEN COUNT(table1.column1) > 5
    THEN
        column1,
        column2,
        column3
        FROM table1
    ELSE
        column1,
        column2,
        column3
        FROM table2
    END

With this code I got something like this:

ERROR:  syntax error at or near ","
LINE 4:   column1, 

Upvotes: 1

Views: 133

Answers (1)

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125244

with c (c) as (select count(c1) from t)
select c1, c2, c3
from t
where (select c from c) > 5
union all
select c1, c2, c3
from r
where (select c from c) <= 5

The corresponding columns must be of the same type. Or be casted to the same type.

WITH clause

UNION clause

Upvotes: 4

Related Questions