Skip to content
Advertisement

Dynamically Modifying Column Names at Query Times in BigQuery

I have a table with columns foo and bar. I want to run a SELECT * on the table and have the result’s columns suffixed by "baz", i.e. the resulting set will have foo_baz and bar_baz columns.
The transformation function (suffix by “baz”) is known a-priori (and will be built into the query), but the column-set of the table are unknown.

Advertisement

Answer

Consider below

execute immediate (
  select 'select ' || string_agg(col || ' as ' || col || '_baz', ', ') || ' from `project.dataset.table`'
  from (
    select regexp_extract_all(to_json_string(t), r'"(.*?)":') cols
    from `project.dataset.table` t limit 1
  ) t, t.cols col 
)    

for example – if applied to data as below

enter image description here

the output will be

enter image description here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement