Creating a query based on record type data field in Google BigQuery
CK 3788 Created at
1,63900
In Google BigQuery, the RECORD type (also known as STRUCT) is a complex data type that allows you to store nested and repeated fields within a table. It helps in organizing hierarchical or structured data efficiently.
Key Features of RECORD Type
Nested Fields (STRUCTs)
A RECORD can contain multiple subfields, each with its own data type.
It is similar to an object or dictionary in programming.
Repeated Fields (Arrays of STRUCTs)
A RECORD field can be repeated, meaning it behaves like an array of structures.
Useful for handling one-to-many relationships.
Improves Query Performance
Helps in reducing joins since related data is stored together.
Allows for efficient querying of nested data.
Example 1: Nested RECORD (STRUCT)
Let's define a table where a customer has an address as a nested field.
Schema Definition
Column Name
Data Type
customer_id
STRING
name
STRING
address
RECORD (STRUCT)
├── street
STRING
├── city
STRING
├── zip
STRING
Creating the Table
CREATE TABLE my_dataset.customers (
customer_id STRING,
name STRING,
address STRUCT<
street STRING,
city STRING,
zip STRING
>
);
Inserting Data
INSERT INTO my_dataset.customers (customer_id, name, address)
VALUES
('C123', 'Alice', STRUCT('123 Main St', 'New York', '10001'));
Querying Nested Data
SELECT customer_id, name, address.city FROM my_dataset.customers;
Example 2: Repeated RECORD (Array of STRUCTs)
Now, let's say a customer can have multiple orders.