🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Snowflake Unstructured Data: Stages, VARIANT, and Documents

đŸŸĸ Free Lesson

Snowflake Unstructured Data

Snowflake Storage

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 VARIANT columns 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.

LayerWhat it holdsTypical choicesFailure it prevents
Cloud storageraw filesS3, Azure Blob, GCSlosing the original bytes
Stagepath plus format and credentialsinternal, external, named, tableguessing delimiters at load time
Processinghow rows are producedCOPY INTO, Snowpipe, streamssilent truncation and type coercion
Storagewhere the result livesVARIANT, typed columns, hybrid tableanalysis 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.

PayloadLanding zoneWhy
JSON events with evolving fieldsVARIANT, then curated subsetschema changes must not block ingestion
Columnar exports for analyticstyped columns via Parquettypes and compression are already in the file
Small reference lookupstyped columns directlyno exploration phase is needed
PDFs, images, audioobject storage plus directory tableparsing is a separate pipeline with its own cost
Long-term archival with queriesIceberg or external tablekeep 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

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Snowflake Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement