Snowflake Unstructured Data
Two very different problems share one platform
"Unstructured data" hides a distinction that decides your entire design. Semi-structured data â JSON logs, Parquet exports, Avro streams â has a shape you can parse, and Snowflake parses it into typed columns on read. Genuinely unstructured data â PDFs, images, video, audio â has no shape at all, and Snowflake stores it as a file in cloud storage while holding a reference and metadata in a table. Confusing the two produces architectures where binary blobs are copied into VARIANT columns and queried as though they were records.
The semi-structured path is where Snowflake is distinctive: you can land raw JSON without declaring a schema, explore its structure with functions, and promote fields into real columns only once you understand them. That schema-on-read workflow removes the chicken-and-egg problem that stalls most ingestion projects, where nothing can be analysed until a schema is agreed and nothing is agreed until the data has been analysed.
- Land semi-structured files into
VARIANTcolumns and explore before you commit. - Promote stable fields into typed columns; leave volatile ones in the variant.
- Keep binaries in object storage and reference them from a table or directory table.
Prerequisites
- !Snowflake tables, schemas, and grants
- !Basic SQL and JSON structure
What You'll Learn
- 1Create reusable file formats for JSON, Parquet, and delimited text
- 2Load from internal and external stages with COPY INTO
- 3Query nested JSON with path notation and flatten arrays
- 4Track files you never parse using directory tables
The four layers of a landing pipeline
Every unstructured ingestion path moves a file through the same four stages: cloud storage holds the bytes, a stage provides an addressable location with format and credential context, a loader moves rows into tables, and the storage layer decides whether the payload becomes typed columns, a variant document, or a file reference. Each layer has its own configuration, and most ingestion incidents trace back to a mismatch between two of them.
| Layer | What it holds | Typical choices | Failure it prevents |
|---|---|---|---|
| Cloud storage | raw files | S3, Azure Blob, GCS | losing the original bytes |
| Stage | path plus format and credentials | internal, external, named, table | guessing delimiters at load time |
| Processing | how rows are produced | COPY INTO, Snowpipe, streams | silent truncation and type coercion |
| Storage | where the result lives | VARIANT, typed columns, hybrid table | analysis blocked on schema debates |
Semi-structured formats differ in useful ways. JSON carries its own schema in every record, which makes it flexible and verbose; Parquet and ORC carry schema once in the file footer and encode values column-wise, which makes them compact and fast to scan. Snowflake reads all of them, but the choice affects storage cost and query speed far more than it affects correctness â so prefer what the upstream system already produces rather than adding a conversion step.
File formats: define once, reuse everywhere
A file format object bundles type, compression, encoding, and error handling into a named, versionable object. Inline FILE_FORMAT options in a COPY statement work for exploration; named formats are what you want in production, because the load statement stops repeating parsing rules that can silently drift between jobs.
-- JSON from an API: strip the outer array so each element becomes a row
CREATE OR REPLACE FILE FORMAT json_api
TYPE = 'JSON'
COMPRESSION = 'AUTO'
STRIP_OUTER_ARRAY = TRUE
TRIM_SPACE = TRUE
IGNORE_UTF8_ERRORS = FALSE
DATE_FORMAT = 'YYYY-MM-DD'
COMMENT = 'API payloads delivered as a JSON array';
-- Parquet: Snowflake infers schema from the file footer
CREATE OR REPLACE FILE FORMAT parquet_events
TYPE = 'PARQUET'
COMPRESSION = 'AUTO'
COMMENT = 'Columnar exports from the streaming pipeline';
-- Delimited text with an explicit encoding and null marker
CREATE OR REPLACE FILE FORMAT csv_legacy
TYPE = 'CSV'
FIELD_DELIMITER = ','
RECORD_DELIMITER = '\n'
SKIP_HEADER = 1
FIELD_OPTIONALLY_ENCLOSED_BY = '"'
NULL_IF = ('', 'NULL', '\\N')
EMPTY_FIELD_AS_NULL = TRUE
ENCODING = 'UTF8'
TRIM_SPACE = TRUE;
Two options cause disproportionate numbers of incidents. STRIP_OUTER_ARRAY decides whether a JSON file containing one big array loads as a single row or as one row per element, and forgetting it produces exactly one row holding the entire payload â which then fails every downstream expectation. IGNORE_UTF8_ERRORS set to TRUE lets malformed bytes pass silently and corrupt names downstream, so leave it FALSE during ingestion and fix the producer instead.
Stages: where files wait
A stage is simply a named location plus the context needed to read it. Internal stages live in Snowflake-managed storage, external stages point at a cloud bucket with a storage integration supplying credentials, and named stages carry a default file format so every read from them inherits the same parsing rules.
-- Named internal stage with a default format
CREATE OR REPLACE STAGE analytics.raw_stage
FILE_FORMAT = json_api
COMMENT = 'Daily API drops for the events pipeline';
PUT file://local/events_2026_03_14.json @analytics.raw_stage/
OVERWRITE = TRUE
AUTO_COMPRESS = TRUE;
LIST @analytics.raw_stage;
-- External stage over S3, authenticated by a storage integration
CREATE OR REPLACE STORAGE INTEGRATION s3_int
TYPE = EXTERNAL_STAGE
STORAGE_PROVIDER = S3
ENABLED = TRUE
STORAGE_AWS_ROLE_ARN = 'arn:aws:iam::123456789012:role/snowflake-reader'
STORAGE_ALLOWED_LOCATIONS = ('s3://acme-landing/events/');
CREATE OR REPLACE STAGE s3_events
URL = 's3://acme-landing/events/'
STORAGE_INTEGRATION = s3_int
FILE_FORMAT = parquet_events;
-- Table stage: one address per table, convenient for small ad-hoc loads
PUT file://local/customers.csv @%customers OVERWRITE = TRUE;
Choose the stage by who owns the producer. When a separate service writes to a bucket on a schedule, an external stage plus a storage integration keeps credentials out of SQL. When your own scripts push files, a named internal stage with PUT is simpler and needs no cloud configuration. Whichever you use, treat the stage path as an interface: renaming a stage silently breaks every COPY that references it.
Loading into VARIANT and reading it back
COPY INTO moves stage files into a table, and for semi-structured sources the target column is VARIANT, which stores the parsed document. From there, colon path notation extracts fields and the double-colon cast turns them into typed values â this is the moment schema-on-read actually happens.
CREATE TABLE IF NOT EXISTS raw.events (
event_id NUMBER AUTOINCREMENT,
payload VARIANT,
source_file STRING,
loaded_at TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
);
COPY INTO raw.events (payload, source_file)
FROM @analytics.raw_stage
FILE_FORMAT = json_api
ON_ERROR = 'CONTINUE'
MATCH_BY_FILE_NAME = FALSE
PURGE = FALSE;
-- Extract and cast
SELECT
payload:event_id::STRING AS event_id,
payload:event_type::STRING AS event_type,
payload:ts::TIMESTAMP_TZ AS event_ts,
payload:device.model::STRING AS device_model,
payload:device.firmware::STRING AS firmware,
payload:active::BOOLEAN AS active,
source_file
FROM raw.events
WHERE payload:event_type::STRING = 'session_start'
AND payload:ts::TIMESTAMP_TZ >= DATEADD(day, -7, CURRENT_TIMESTAMP());
-- Null-safe extraction: get_object to avoid NULL chains
SELECT
get_path(payload, 'device/model')::STRING AS device_model,
payload:"odd key"::STRING AS quoted_field
FROM raw.events
LIMIT 20;
-- Promote the stable fields into a typed table
CREATE OR REPLACE TABLE curated.events AS
SELECT
payload:event_id::STRING AS event_id,
payload:ts::TIMESTAMP_TZ AS event_ts,
payload:event_type::STRING AS event_type,
payload:device.model::STRING AS device_model
FROM raw.events
WHERE payload:event_id IS NOT NULL;
Two habits make this workflow safe. Always cast explicitly, because a variant comparison follows different rules than a typed one and an implicit comparison can quietly return no rows. And keep the raw layer immutable: raw.events is your replay capability, so anything you get wrong in curated can be rebuilt without re-fetching from the source system.
Flattening arrays without losing the parent
Nested arrays are where flat tables and real documents diverge. LATERAL FLATTEN expands an array into rows while OBJECT_AGG or aggregation can collapse them back, so the same table supports both "one row per event" and "one row per user with an array of orders".
-- One row per order line
SELECT
e.payload:user_id::STRING AS user_id,
f.value:product::STRING AS product,
f.value:quantity::NUMBER AS quantity,
f.value:price::NUMBER AS price,
f.value:quantity::NUMBER * f.value:price::NUMBER AS line_total,
f.index AS line_no
FROM raw.events e,
LATERAL FLATTEN(input => e.payload:orders) f
WHERE e.payload:orders IS NOT NULL;
-- Collapse back: one row per user with an aggregate array
SELECT
payload:user_id::STRING AS user_id,
COUNT(*) AS order_count,
SUM(f.value:price::NUMBER) AS total_spend,
ARRAY_AGG(f.value:product::STRING) AS products
FROM raw.events e,
LATERAL FLATTEN(input => e.payload:orders) f
GROUP BY 1;
-- Flatten a JSON object's keys when the structure varies per record
SELECT
e.payload:user_id::STRING AS user_id,
kv.key AS metric_name,
kv.value::NUMBER AS metric_value
FROM raw.events e,
LATERAL FLATTEN(input => e.payload:metrics) kv;
-- Recursive flattening for deeply nested documents
SELECT
f1.value:sku::STRING AS sku,
f2.value:tag::STRING AS tag
FROM raw.events e,
LATERAL FLATTEN(input => e.payload:items, RECURSIVE => TRUE) f1
LEFT JOIN LATERAL FLATTEN(input => f1.value:tags) f2 ON TRUE;
Watch the row multiplication. Flattening two arrays in one statement multiplies them, so an event with three orders and four tags produces twelve rows â correct for some questions, catastrophic for a COUNT(DISTINCT user_id) if you did not expect it. When you must flatten two arrays, flatten one, aggregate, then flatten the second in a separate CTE.
Directory tables: metadata for files you never parse
Some files should never become rows. Images, contracts, and scan archives belong in object storage with their metadata queryable â that is exactly what a directory table provides: a periodically refreshed index of the files in a stage, exposed through a normal SQL view.
CREATE OR REPLACE TABLE raw.documents (
doc_id NUMBER AUTOINCREMENT,
relative_path STRING,
file_url STRING,
uploaded_by STRING,
uploaded_at TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()
) DIRECTORY = (ENABLE = TRUE);
-- Refresh the directory index after files land
ALTER TABLE raw.documents REFRESH;
-- Query the file inventory as if it were a table
SELECT
relative_path,
size,
last_modified,
md5
FROM TABLE(information_schema.directory_table())
WHERE table_name = 'DOCUMENTS'
ORDER BY last_modified DESC;
-- Build presigned URLs for a client that needs to fetch a file
SELECT
relative_path,
BUILD_PRESIGNED_URL(@analytics.raw_stage, relative_path, 3600) AS link
FROM TABLE(information_schema.directory_table())
WHERE table_name = 'DOCUMENTS'
AND relative_path LIKE 'contracts/%';
-- Join the directory index with application metadata
SELECT d.relative_path, d.size, m.uploaded_by, m.doc_type
FROM TABLE(information_schema.directory_table()) d
JOIN raw.documents_meta m ON d.relative_path = m.relative_path;
Directory tables index a stage rather than a table's own storage, which means the refresh is explicit â run it on a schedule or after each upload batch, or the query view will lag reality. For document-heavy workloads this pattern gives you the best of both worlds: the bytes stay cheap in object storage, and discovery, access control, and lifecycle rules all operate on ordinary SQL rows.
Choosing where a file should land
The decision that most often needs revisiting is whether a payload belongs in VARIANT, in typed columns, or as a file reference. The table below is the rule of thumb worth writing into a team's ingestion standards.
| Payload | Landing zone | Why |
|---|---|---|
| JSON events with evolving fields | VARIANT, then curated subset | schema changes must not block ingestion |
| Columnar exports for analytics | typed columns via Parquet | types and compression are already in the file |
| Small reference lookups | typed columns directly | no exploration phase is needed |
| PDFs, images, audio | object storage plus directory table | parsing is a separate pipeline with its own cost |
| Long-term archival with queries | Iceberg or external table | keep open formats for portability |
A useful corollary: do not promote a field into a typed column until its semantics have been stable for several delivery cycles. Early promotion is how a column ends up half-null and half-typed, with a TO_DATE() that fails on one row out of ten thousand.
Mistakes that break ingestion quietly
Common Mistakes
Leaving STRIP_OUTER_ARRAY at its default for an array payload
Fix: Set it explicitly and confirm the row count; a forgotten flag loads one row containing the whole file.
Setting IGNORE_UTF8_ERRORS to TRUE to make a load succeed
Fix: Keep it FALSE and fix the producer, otherwise malformed characters reach reports undetected.
Comparing variant values without casting
Fix: Cast with the double-colon operator so filters use typed comparison semantics.
Flattening two arrays in the same statement without noticing the row product
Fix: Flatten one, aggregate, then flatten the second in a later CTE.
Overwriting the raw layer once curated tables look correct
Fix: Keep raw immutable; it is the only replay path when a transformation is wrong.
Storing PDFs or images inside VARIANT columns
Fix: Reference object storage from a table or directory table instead of copying binaries into rows.
Relying on a directory table that is never refreshed
Fix: Schedule ALTER TABLE ... REFRESH alongside the upload job so the index tracks the stage.
Practices that scale an unstructured pipeline
Best Practices
- Define named file formats once and reference them from every load.
- Keep a raw VARIANT layer immutable and build curated tables on top of it.
- Cast every extracted field explicitly and document the target type.
- Validate a sample of each new delivery shape before the first production load.
- Use Snowpipe for continuous streams and COPY INTO for scheduled batches.
- Partition curated tables by load date so replays touch a bounded amount of data.
- Track file metadata with directory tables instead of maintaining a parallel inventory database.
- Prefer Parquet for analytical exports and JSON only where the producer already emits it.
Key takeaways
Key Takeaways
- Semi-structured data becomes queryable rows; genuinely unstructured files stay in object storage with references.
- Named file formats make parsing rules reusable and reviewable instead of scattered across COPY statements.
- Stages add credentials, default formats, and a stable address to a cloud path.
- COPY INTO with a VARIANT column is where schema-on-read begins; explicit casts finish it.
- LATERAL FLATTEN expands arrays, and flattening two at once multiplies rows.
- Promote fields into typed columns only after their shape has been stable for several cycles.
- Directory tables give SQL access to a file inventory, provided the refresh runs.
- The raw layer is your replay capability â never overwrite it.
Where to go next
- Semi-Structured Data Handling â deeper coverage of path notation and parsing functions.
- Snowpipe Ingestion â continuous loading from a stage instead of scheduled batches.
- Data Lakehouse â Iceberg tables when open formats matter.
- Data Quality â validating what lands in the raw layer before it reaches anyone.