Skip to main content

Query JSON in S3 from Snowflake with an external table

Query newline-delimited JSON in S3 with a Snowflake external table. A storage integration grants access to the bucket, a stage identifies the files and partition columns let Snowflake select files by their object keys. Both plain and gzipped JSON work.

The files​

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

s3://<bucket>/<prefix>/date=2026-11-19/hour=08/<file>.ndjson.gz

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

{"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}]}}

Connect Snowflake to the bucket​

A storage integration holds an IAM role that Snowflake assumes to read the bucket, so no access key is stored in Snowflake. Creating one needs ACCOUNTADMIN or a role with the CREATE INTEGRATION privilege:

CREATE STORAGE INTEGRATION s3_json_int
TYPE = EXTERNAL_STAGE
STORAGE_PROVIDER = 'S3'
ENABLED = TRUE
STORAGE_AWS_ROLE_ARN = 'arn:aws:iam::<account_id>:role/snowflake-json-read'
STORAGE_ALLOWED_LOCATIONS = ('s3://<bucket>/<prefix>/');

DESC INTEGRATION s3_json_int;

DESC INTEGRATION returns STORAGE_AWS_IAM_USER_ARN and STORAGE_AWS_EXTERNAL_ID. Put both in the role's trust policy:

{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"AWS": "<STORAGE_AWS_IAM_USER_ARN>"},
"Action": "sts:AssumeRole",
"Condition": {"StringEquals": {"sts:ExternalId": "<STORAGE_AWS_EXTERNAL_ID>"}}
}]
}

Reading needs s3:GetObject and s3:GetObjectVersion on arn:aws:s3:::<bucket>/<prefix>/*, and s3:ListBucket and s3:GetBucketLocation on arn:aws:s3:::<bucket>. Give the role nothing more. The full walkthrough, including the IAM console steps, is in Configuring a Snowflake storage integration to access Amazon S3.

Create a file format and a stage​

The file format says how to parse the files. TYPE = JSON reads NDJSON, one document per line, and COMPRESSION = GZIP decompresses them. The default, AUTO, also detects gzip; naming it makes the intent plain:

CREATE SCHEMA IF NOT EXISTS ext;

CREATE FILE FORMAT ext.ndjson_gz
TYPE = JSON
COMPRESSION = GZIP;

CREATE STAGE ext.json_stage
STORAGE_INTEGRATION = s3_json_int
URL = 's3://<bucket>/<prefix>/'
FILE_FORMAT = ext.ndjson_gz;

If each file is one large JSON array instead of one object per line, add STRIP_OUTER_ARRAY = TRUE to the file format so each element becomes a row. Creating the stage needs USAGE on the integration: GRANT USAGE ON INTEGRATION s3_json_int TO ROLE <role>.

Check what the stage sees before building a table on it. LIST shows the objects, and a query on the stage reads them directly, with each line in $1 as a VARIANT:

LIST @ext.json_stage;

SELECT METADATA$FILENAME, $1:received_at::VARCHAR AS received_at, $1:data.event::VARCHAR AS event
FROM @ext.json_stage (FILE_FORMAT => 'ext.ndjson_gz', PATTERN => '.*[.]ndjson[.]gz')
LIMIT 5;

METADATA$FILENAME is the object's path in the stage. Look at it here: the partition columns below are parsed from it. See Querying data in staged files.

Create the external table​

Every external table has a VALUE column, a VARIANT holding one line of a file. On top of it you declare two kinds of columns:

  • Partition columns are expressions on METADATA$FILENAME, the object key. Snowflake computes them when it registers a file, and a filter on them skips whole files.
  • Virtual columns are expressions on VALUE, cast to a type. They are computed at query time and save you writing the cast in every query.
CREATE EXTERNAL TABLE ext.events (
file_date DATE AS TO_DATE(SPLIT_PART(SPLIT_PART(METADATA$FILENAME, '/', -3), '=', 2)),
file_hour NUMBER AS TO_NUMBER(SPLIT_PART(SPLIT_PART(METADATA$FILENAME, '/', -2), '=', 2)),
signal VARCHAR AS (VALUE:signal::VARCHAR),
received_at TIMESTAMP_TZ AS (VALUE:received_at::TIMESTAMP_TZ)
)
PARTITION BY (file_date, file_hour)
LOCATION = @ext.json_stage/
PATTERN = '.*date=.*[.]ndjson[.]gz'
FILE_FORMAT = (FORMAT_NAME = 'ext.ndjson_gz')
AUTO_REFRESH = TRUE;
  • SPLIT_PART with a negative part number counts from the end of the string, so -2 is the hour=08 folder and -3 is date=2026-11-19, however deep <prefix> is. The outer SPLIT_PART(..., '=', 2) keeps the value after =.
  • PATTERN is a regular expression on the object path. Here it leaves out anything outside the date= folders.
  • An external table does not inherit the stage's file format, so FILE_FORMAT is repeated.
  • REFRESH_ON_CREATE defaults to TRUE: the CREATE registers the files already in the bucket. For a location with around a million files or more, Snowflake recommends setting it to FALSE and refreshing by subpath instead.

External tables are read-only. You can query them, join them and create views on them, but not insert or update.

Query the VARIANT column​

A field inside VALUE is VALUE:<field>: a colon after the column name, then dots for nested objects. Element names are case-sensitive; column names are not. Without a cast the result is a VARIANT, and strings come back in double quotes, so cast with ::.

Events by name, with revenue from order.paid, for November:

SELECT VALUE:data.event::VARCHAR AS event,
COUNT(*) AS events,
SUM(VALUE:data.cents::NUMBER) / 100 AS revenue_usd
FROM ext.events
WHERE signal = 'event'
AND file_date >= '2026-11-01'
GROUP BY event
ORDER BY events DESC;

The filter on file_date decides which files are read. A filter on a field inside the JSON, such as signal, still reads every file the partitions allow, so on a large bucket always filter on the partition columns first.

Users who viewed the pricing page, by plan:

SELECT VALUE:data.plan::VARCHAR AS plan,
COUNT(DISTINCT VALUE:data.user_id::VARCHAR) AS users
FROM ext.events
WHERE VALUE:data.event::VARCHAR = 'page.view'
AND VALUE:data.path::VARCHAR = '/pricing'
GROUP BY plan
ORDER BY users DESC;

A path that a line does not have returns NULL rather than an error, so lines of different shapes can share one table.

Unnest nested arrays​

Each order.paid event carries an items array. LATERAL FLATTEN returns one row per element, with the element in value:

SELECT e.VALUE:data.order_id::VARCHAR AS order_id,
i.value:sku::VARCHAR AS sku,
i.value:qty::NUMBER AS qty
FROM ext.events e,
LATERAL FLATTEN(input => e.VALUE:data.items) i
WHERE e.VALUE:data.event::VARCHAR = 'order.paid'
ORDER BY order_id
LIMIT 3;

Querying semi-structured data covers bracket notation, keys with special characters and GET_PATH.

Keep the table current​

The table's file list is metadata. A file added to the bucket is not queryable until that metadata is refreshed. There are two ways.

Auto-refresh from S3 events. With AUTO_REFRESH = TRUE, Snowflake listens on an SQS queue it owns. Find the queue and point an S3 event notification at it:

SHOW EXTERNAL TABLES LIKE 'EVENTS' IN SCHEMA ext;

Copy the ARN in the notification_channel column. In the bucket's properties, add an event notification for <prefix>/ with the event types ObjectCreate (All) and ObjectRemoved, destination SQS queue, and that ARN. Snowflake usually uses one queue per account and AWS region, shared by its buckets in that region. S3 does not allow overlapping queue configurations on one bucket; if a notification on that prefix already exists, route both through an SNS topic and create the table with AWS_SNS_TOPIC, as Refresh external tables automatically for Amazon S3 describes.

Auto-refresh is billed as Snowpipe, and the cost grows with the number of files added. Many small files cost more to register than a few large ones; Snowflake suggests 16 to 256 MB per file for formats other than Parquet.

Manual refresh. Without event notifications, for example on S3-compatible storage where auto-refresh is not supported, refresh on a schedule. A manual refresh is a cloud-services operation. A relative path limits it to one folder:

ALTER EXTERNAL TABLE ext.events REFRESH;
ALTER EXTERNAL TABLE ext.events REFRESH 'date=2026-11-23/';

Either way, a refresh also removes deleted files from the metadata and picks up changed ones.

Make repeated queries faster​

Every query on an external table downloads and parses the gzip JSON again. If you query the same days often:

  • Load the files into a native table with a VARIANT column, with Snowpipe or a scheduled COPY INTO. Snowflake keeps load history per file, so reruns do not load a file twice. The Snowflake querying guide has the statements.
  • Or create a materialized view over the external table with the fields you use. Materialized views need Enterprise Edition.

Where Send2Bucket fits​

Send2Bucket is a hosted endpoint for JSON events and OpenTelemetry that writes them to your own bucket in this layout, so everything above applies. Per Delivery format:

  • Each delivery batch is one gzip NDJSON object at <prefix>/s2b/stream=<stream_id>/date=YYYY-MM-DD/hour=HH/<delivery_batch_id>.ndjson.gz. The partition expressions above work unchanged, and SPLIT_PART(..., '/', -4) adds the stream.
  • Point the stage at s3://<bucket>/<prefix>/s2b/ and use PATTERN = '.*stream=.*[.]ndjson[.]gz', which leaves out the test objects under s2b/_verify/.
  • The JSON you sent is in VALUE:data, unchanged. signal is event, log, span or metric, and received_at is when Send2Bucket accepted the request.
  • 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.
  • Send2Bucket's role writes and reads but cannot delete, and a retried write puts identical bytes under the same key. ObjectRemoved events then only matter if your own lifecycle rules expire objects.
  • A stream with steady traffic gets a new object at least every 60 seconds on Trial, Pro and Team and every 10 seconds on Free, sooner at 16 MiB (delivery format), so auto-refresh registers many small files. If the per-file cost matters, load into a native table instead.

The Snowflake querying guide has the full setup for Send2Bucket objects in S3, Cloud Storage and S3-compatible storage, the external table with a stream_id column, Snowpipe loading, Iceberg and S3 Tables destinations, and queries for logs and spans. To send data in the first place, start with Quick start.

Notes​

  • Partitions computed from METADATA$FILENAME cannot later be switched to partitions you add by hand (PARTITION_TYPE = USER_SPECIFIED), or back. Tables with hand-added partitions cannot auto-refresh.
  • If a file fails to parse during a scan, Snowflake skips it and continues with the next file.
  • Snowflake caches the integration's temporary credentials for up to 60 minutes, so access you revoke in IAM can last that long.
  • Other roles that query the table need USAGE on the database and schema, USAGE and READ on the stage, USAGE on the file format, and SELECT on the external table.
  • For Cloud Storage or Azure, the integration, stage and table look the same; auto-refresh uses a notification integration instead of SQS. See Introduction to external tables.