0

I want to create a RECORD as the outcome of a select in BigQuery standard SQL.

If I run this SQL snippet,

WITH 
mock_data AS (
    SELECT 'foo1' as foo, 'bar1' as bar, 'bla1' as bla UNION ALL
    SELECT 'foo2' as foo, 'bar2' as bar, 'bla2' as bla
)
SELECT 
    *,
    STRUCT(
        m.foo as foo,
        m.bar as bar
    ) as foobar
FROM mock_data m

the output of foobar is an array of records, not a single record. output of the query

How could I have the foobar column be a single record and not an array of records? Thanks a lot in advance!

2 Answers 2

2

It is a single record - not an array

You can clearly see this in JSON Tab

enter image description here

Also you can go to "Job Information" Tab

enter image description here

and click on "Temporary Table" to see the schema of output

enter image description here

In the BigQuery IDE that I am using - it is even more visible

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Interesting! Thanks a lot Michail I got confused by how it is displayed in the results, with "row 1" as if there could be various rows. Solved!
1

The UNNEST operator flattens arrays into rows, i.e. it breaks an array into several rows. STRUCT elements get broken down into multi-column records, which is what I think you require. Try something like this out:

SELECT
   *,
   UNNEST(
      STRUCT(
        m.foo as foo,
        m.bar as bar
      ) as foobar
   )

1 Comment

Thanks a lot @Blend3rman! Your code seems to be wrong syntactically, if I try the following adaptation it complains about UNNEST needing to be done on an array and not a single struct: WITH mock_data AS ( SELECT 'foo1' as foo, 'bar1' as bar, 'bla1' as bla UNION ALL SELECT 'foo2' as foo, 'bar2' as bar, 'bla2' as bla ) SELECT *, (SELECT * FROM UNNEST(STRUCT( m.foo as foo, m.bar as bar ))) as foobar FROM mock_data m

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.