How do I perform an IF...THEN in an SQL SELECT in snowflake?
Snowflake as for today does not support SQL-based procedural logic.
The query could be rewritten as:
SELECT *
FROM (SELECT *, 1 AS priority FROM table2
UNION ALL
SELECT *, 2 AS priority FROM table1) sub
QUALIFY piority = MIN(priority) OVER();
-- or
SELECT * FROM table2
UNION ALL
SELECT * FROM table1 WHERE NOT EXISTS (SELECT 1 FROM table2);
Assumption: both tables have the same structure.
EDIT:
Using Snowflake scripting it is possible to use branching structures:
declare
res RESULTSET;
query VARCHAR;
tab_name STRING;
begin
if (EXISTS(select 1 from table2)) then
tab_name := 'table2';
else
tab_name := 'table1';
end if;
query := 'SELECT * FROM ' || :tab_name;
res := (execute immediate :query);
return table(res);
end;