# Create a BigQuery external table over JSON in Cloud Storage

Create an external table in [BigQuery](../querying/bigquery.md) to query gzip NDJSON files in Cloud Storage. Define columns explicitly or use schema autodetection. If the files use Hive-style paths, expose their partition keys as columns so queries can skip unrelated files.

## The files

The examples read gzip NDJSON objects under date and hour prefixes:

```text
gs://<bucket>/events/date=2026-11-19/hour=08/<file>.ndjson.gz
```

Each line is one JSON object. These come from Send2Bucket's sample dataset, so each event sits inside a small envelope; your own lines will have other fields:

```json
{"v":1,"delivery_batch_id":"dlv_00361ph3ha13ummf535glgajq8b1s","stream_id":"3f6c2a9e-8b1d-4e7a-9c55-0d2b7e41a8f3","batch_id":"bat_00361ph3aqk2686au6sq08gq21ah8","received_at":"2026-11-22T23:50:11.890211Z","signal":"event","data":{"event":"order.paid","user_id":"usr_0003","plan":"team","ts":"2026-11-19T13:05:00Z","order_id":"ord_20005","cents":19900,"currency":"usd","items":[{"sku":"sku_1","qty":1}]}}
```

## Before you start

- The dataset that holds the external table must be in the bucket's location: a bucket in `us-central1` needs a dataset in `us-central1` or the `US` multi-region. See [location considerations](https://cloud.google.com/bigquery/docs/external-tables#storage-location-considerations).
- Creating the table needs `bigquery.tables.create` (BigQuery Data Editor has it). Querying it needs read on the table and `storage.objects.get` and `storage.objects.list` on the bucket. A [BigLake table](https://cloud.google.com/bigquery/docs/biglake-intro) moves the bucket permission to a connection, so users need access to the table only.

```sql
CREATE SCHEMA IF NOT EXISTS json_demo OPTIONS (location = '<location>');
```

## Create the table with autodetect

Leave out the column list and BigQuery detects the schema. `WITH PARTITION COLUMNS` without a list detects the `key=value` folders as partition columns:

```sql
CREATE OR REPLACE EXTERNAL TABLE json_demo.events_auto
WITH PARTITION COLUMNS
OPTIONS (
  format = 'NEWLINE_DELIMITED_JSON',
  compression = 'GZIP',
  uris = ['gs://<bucket>/events/*'],
  hive_partition_uri_prefix = 'gs://<bucket>/events'
);
```

- `compression = 'GZIP'` is required for `.gz` files. Without it, BigQuery treats the files as uncompressed. The setting applies to every file the table reads, so keep uncompressed files under another prefix.
- Each URI can hold one `*`, after the bucket name. `gs://<bucket>/events/*.ndjson.gz` also works and skips other files.
- `hive_partition_uri_prefix` is the part of the path before the first `key=value` folder, without the wildcard.

Check what it found:

```bash
bq show --schema --format=prettyjson <project>:json_demo.events_auto
```

Autodetect picks a random file and reads up to its first 500 lines ([schema auto-detection](https://cloud.google.com/bigquery/docs/schema-detect)). Nested objects become `RECORD` columns and arrays become `REPEATED` ones, and strings that look like numbers, booleans or dates are converted. A field that appears only in other files is missing from the schema, and every file the URI matches must share a compatible schema. Autodetect is fine for a first look at uniform files; for a table people depend on, declare the schema.

## Declare the schema

List the columns you need, and type the partition columns in the order they appear in the path:

```sql
CREATE OR REPLACE EXTERNAL TABLE json_demo.events (
  received_at TIMESTAMP,
  signal STRING,
  data STRUCT<
    event STRING,
    user_id STRING,
    plan STRING,
    path STRING,
    order_id STRING,
    cents INT64,
    items ARRAY<STRUCT<sku STRING, qty INT64>>
  >
)
WITH PARTITION COLUMNS (date DATE, hour INT64)
OPTIONS (
  format = 'NEWLINE_DELIMITED_JSON',
  compression = 'GZIP',
  uris = ['gs://<bucket>/events/*'],
  hive_partition_uri_prefix = 'gs://<bucket>/events',
  ignore_unknown_values = true,
  require_hive_partition_filter = true
);
```

- `ignore_unknown_values = true` skips keys that are not in the schema, such as `delivery_batch_id` and `data.currency` here. Without it, a line with an extra key is an error.
- `require_hive_partition_filter = true` rejects any query without a filter on `date` or `hour`, so nobody scans the whole bucket by accident.
- `received_at` parses as a `TIMESTAMP` because it is RFC 3339 with a `Z`. See [JSON data types](https://cloud.google.com/bigquery/docs/loading-data-cloud-storage-json#details_of_loading_json_data) for the accepted formats.
- Partition column names cannot match a column in the files. The partition key cannot be changed after the table is created; recreate the table instead.

The table holds no data. Each query lists the matching folders and reads their files.

## Query nested fields

`STRUCT` fields take dot notation. Events by name, with revenue from `order.paid`, for one month:

```sql
SELECT data.event AS event,
       COUNT(*) AS events,
       SUM(data.cents) / 100 AS revenue_usd
FROM json_demo.events
WHERE date BETWEEN DATE '2026-11-01' AND DATE '2026-11-30'
  AND signal = 'event'
GROUP BY event
ORDER BY events DESC;
```

The filter on `date` decides which folders are read. A filter on a field inside the JSON, such as `signal`, still reads every file in those folders.

`UNNEST` turns the `items` array into one row per element:

```sql
SELECT data.order_id, item.sku, item.qty
FROM json_demo.events, UNNEST(data.items) AS item
WHERE date >= DATE '2026-11-01'
  AND data.event = 'order.paid'
ORDER BY data.order_id
LIMIT 3;
```

To find which file a row came from, select the `_FILE_NAME` pseudocolumn. It needs an alias:

```sql
SELECT _FILE_NAME AS file, COUNT(*) AS records
FROM json_demo.events
WHERE date = DATE '2026-11-19'
GROUP BY file
ORDER BY file;
```

## Keep changing fields as JSON

A `STRUCT` schema fits fields that keep their shape. When the files mix record shapes, or new keys keep arriving, keep the variable part as BigQuery's `JSON` type and pick fields at query time. Google documents `JSON` columns for load jobs into native tables; its external table pages do not say an NDJSON external table accepts one. The approach that works with documented options is to read each line as one string with the CSV reader, then parse it:

```sql
CREATE OR REPLACE EXTERNAL TABLE json_demo.event_lines (line STRING)
WITH PARTITION COLUMNS (date DATE, hour INT64)
OPTIONS (
  format = 'CSV',
  field_delimiter = '\x01',
  quote = '',
  compression = 'GZIP',
  uris = ['gs://<bucket>/events/*'],
  hive_partition_uri_prefix = 'gs://<bucket>/events'
);
```

Quoting is off, and the delimiter is byte `0x01`, which valid JSON never holds unescaped, so each line arrives whole. `PARSE_JSON` turns it into a `JSON` value. Field access (`doc.data.event`) returns `JSON`; `JSON_VALUE` returns a string you can group on, and `LAX_INT64` a number you can add:

```sql
SELECT JSON_VALUE(doc.data.event) AS event,
       COUNT(*) AS events,
       SUM(LAX_INT64(doc.data.cents)) / 100 AS revenue_usd
FROM (
  SELECT SAFE.PARSE_JSON(line) AS doc
  FROM json_demo.event_lines
  WHERE date >= DATE '2026-11-01'
)
WHERE JSON_VALUE(doc.signal) = 'event'
GROUP BY event
ORDER BY events DESC;
```

`JSON_QUERY_ARRAY` turns a JSON array into an `ARRAY<JSON>` for `UNNEST`:

```sql
SELECT JSON_VALUE(doc.data.order_id) AS order_id,
       JSON_VALUE(item.sku) AS sku,
       LAX_INT64(item.qty) AS qty
FROM (
  SELECT SAFE.PARSE_JSON(line) AS doc
  FROM json_demo.event_lines
  WHERE date >= DATE '2026-11-01'
), UNNEST(JSON_QUERY_ARRAY(doc.data.items)) AS item
WHERE JSON_VALUE(doc.data.event) = 'order.paid';
```

`JSON` values cannot be compared, so `GROUP BY` and `WHERE` need `JSON_VALUE` or a conversion function around them. A path that does not exist returns `NULL`, not an error, so check spelling when a column comes back empty.

## Copy to a native table

An external table reads and parses the files on every query. Google's [JSON limitations](https://cloud.google.com/bigquery/docs/loading-data-cloud-storage-json#limitations) note that BigQuery cannot read a gzip file in parallel and that one gzip file can be at most 4 GB. If you query the same days repeatedly, copy them once into a native table, partitioned and clustered:

```sql
CREATE TABLE json_demo.events_native
PARTITION BY DATE(received_at)
CLUSTER BY signal
AS
SELECT received_at, signal, data
FROM json_demo.events
WHERE date BETWEEN DATE '2026-11-01' AND DATE '2026-11-30';
```

Run it again for a new month with `INSERT INTO json_demo.events_native SELECT ...`. Copying the same days twice stores them twice, so keep track of what you copied.

## Where Send2Bucket fits

Send2Bucket is a hosted endpoint for JSON events and OpenTelemetry that writes them to your own Cloud Storage bucket as gzip NDJSON, so everything above applies. Per [Delivery format](../delivery-format.md):

- Each delivery batch is one object at `<prefix>/s2b/stream=<stream_id>/date=YYYY-MM-DD/hour=HH/<delivery_batch_id>.ndjson.gz`. That is three partition keys: `WITH PARTITION COLUMNS (stream STRING, date DATE, hour INT64)`, with `hive_partition_uri_prefix = 'gs://<bucket>/<prefix>/s2b'`.
- Use `uris = ['gs://<bucket>/<prefix>/s2b/stream=*']`. It keeps the destination's test objects under `s2b/_verify/` out of the table.
- The JSON you sent is in `data`, unchanged. `signal` is `event`, `log`, `span` or `metric`, and OpenTelemetry lines add `resource` and `scope`. Logs, spans and metrics have different shapes, so one `STRUCT` schema does not fit them all; the line-as-string table above does.
- `date` and `hour` are the UTC hour the records arrived, not the time inside them. To select by event time, filter on your own timestamp and widen the `date` range to catch late arrivals.

The [BigQuery querying guide](../querying/bigquery.md) has the `s2b.raw_lines` external table and `s2b.records` view built this way, a scheduled `LOAD DATA` into a native table, and queries for logs, spans and metrics. [OpenTelemetry to Google Cloud Storage](./opentelemetry-to-gcs.md) covers granting Send2Bucket's service account access to the bucket and pointing exporters at it.

## Notes

- With on-demand pricing, BigQuery bills the bytes each query reads from Cloud Storage. A dry run of a query on an external table can report 0 bytes even when the query reads data ([external table limitations](https://cloud.google.com/bigquery/docs/external-tables#limitations)). Filter on the partition columns.
- External tables are read-only and cannot be clustered. BigQuery does not guarantee consistent results when files change while a query runs.
- Clean up with `DROP SCHEMA json_demo CASCADE;`. Dropping an external table leaves the files in the bucket.
