1

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, 
5
  • Did you tried put selected columns inside a simple bracket? SELECT CASE WHEN COUNT(var1) > 5 THEN (column1, column2, column3 FROM table1) ELSE ( column1, column2, column3 FROM table2) END. I have not tried, it is a wild guess. Commented Aug 1, 2016 at 10:02
  • @Santhucool with brackets the error message slightly differs but it still doesn't work : ERROR: syntax error at or near "FROM" LINE 4: FROM table1) Commented Aug 1, 2016 at 10:18
  • What is var1? Is it a table column? If yes, from which table? Commented Aug 1, 2016 at 10:20
  • @Laurenz Albe in this specific case var1 = table1.column1 Commented Aug 1, 2016 at 10:29
  • @Qvery did you tried sub query inside brackets I mean select. Commented Aug 1, 2016 at 11:04

1 Answer 1

4
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

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.