In short - this is not possible (with pure SQL at least) in Presto/Trino.
SQL in general is not designed to return dynamic column sets. And while some db/query engines may allow some scripting to dynamically generate and execute query (or another option - dynamic pivoting) - Presto/Trino does not. The only option is to use some kind of outside scripting (which seems to already be the case) - i.e. query the columns:
select *
from information_schema.columns
where table_name = 'table_name'
-- AND column_name ... -- maybe filter here
And then process the results and then generate the query and execute it.
Or if you already know the columns - just dynamically create the query string.
P.S.
- The provided query is not a valid one in Presto/Trino (even if you substitute the
{{...}}
)
- but the execution of query stopped once first condition has met - yes, that is exactly how the CASE is designed to work - it executes the first
true
condition and then returns it's matched result. Basically it is SQL way to say if-else
- Another option you might want to consider - pivoting and/or using
maps
:
-- sample data
WITH dataset(x_1,x_2,y_1,y_2, z_1) as (
values (1,2,3,4,5),
(1,2,3,4,5),
(1,2,3,4,5)
)
-- query
select map_filter(
map(array['x_1', 'x_2', 'y_1', 'y_2', 'z_1'], array[x_1, x_2, y_1, y_2, z_1]),
(k,v) -> any_match(array['x', 'y'], c -> k like c || '%') -- change array['x', 'y'] to contain needed prefixes
)
from dataset;
Output:
_col0
------------------------------
{x_2=2, y_1=3, x_1=1, y_2=4}
{x_2=2, y_1=3, x_1=1, y_2=4}
{x_2=2, y_1=3, x_1=1, y_2=4}