What you will be able to do
- Tell structured, semi-structured and unstructured data apart and name the retrieval path each one takes
- Write a CSV file format that handles header rows and delimiters inside quoted values
- Query staged files directly with positional $n columns, a named file format and METADATA$ pseudo-columns
- Load semi-structured files into VARIANT, get past the 128 MB value limit with STRIP_OUTER_ARRAY, and read XML elements with XMLGET
- List unstructured files with a directory table and pick the right URL type (scoped, file or pre-signed) for an audience
Key concept
Stage plus file format — Every file Snowflake retrieves sits on a stage, which is an internal or external cloud storage location. A file format tells Snowflake how to parse those files. The data category decides what happens next: parse the files into columns, parse them into a VARIANT hierarchy, or leave them unparsed and hand out URLs.
1.Three categories of source data
Before you retrieve data in Snowflake, work out which category it belongs to, because the category decides the path. Structured data such as a CSV file follows a strict tabular schema and goes straight into ordinary table columns. Semi-structured data (JSON, Avro, ORC, Parquet and XML) carries its own tags and nesting instead of a fixed schema. New attributes can appear at any time, and two records of the same kind can hold different fields. Unstructured data, such as documents, images, audio and video, has no inherent schema. A PNG file does follow a documented internal format, but that format says nothing about what the picture shows.
All three categories are read from the same place: a stage. An internal stage is storage that Snowflake manages, including the user stage every user gets and the table stage every table gets. An external stage points at your own Amazon S3, Google Cloud Storage or Microsoft Azure location. Snowflake cannot read files held in archival storage classes that need restoring first, such as S3 Glacier Deep Archive. The category only changes what you do once a file is on the stage.
| Category | Typical formats | How Snowflake retrieves it |
|---|---|---|
| Structured | CSV (delimited text) | Parsed by a CSV file format into positional fields $1, $2, … that map to table columns |
| Semi-structured | JSON, Avro, ORC, Parquet, XML | Parsed by the matching file format TYPE into a VARIANT hierarchy, or split into separate columns |
| Unstructured | Documents, images, audio, video | Not parsed into rows: listed through a directory table and opened through scoped, file or pre-signed URLs |
Checkpoint 1 of 8· Match them up
Match each category of source data to how Snowflake retrieves it from a stage
Tap a term, then the definition that fits it.
The category decides what happens after a file is on the stage. CSV follows a fixed schema, so it maps to columns. Self-describing nested formats become a VARIANT hierarchy, or are split into columns. Files with no inherent schema stay unparsed and are reached through URLs.
“Snowflake can build the hierarchy for you and store it in a VARIANT.”Source: docs.snowflake.com
2.Describing a CSV file with a file format
A file format tells Snowflake how to split a stream of text into records and fields. If you give none, Snowflake assumes CSV, with a comma between fields and a new line between records. That default is often right, but it is wrong in exactly the cases that produce bad loads. CREATE FILE FORMAT creates a named, reusable format that a stage, a COPY statement or a query can reference.
Three CSV options decide whether each value lands in the right column:
FIELD_DELIMITERis the character that separates fields. Keep the comma default for a comma-separated file. Setting it to';'on a comma file means no delimiter is ever found, so each whole line arrives as one field.SKIP_HEADER = <integer>is the number of lines skipped at the start of the file. A file with one header row needsSKIP_HEADER = 1. With 0, the column names arrive as a row of data.FIELD_OPTIONALLY_ENCLOSED_BY = '"'is the character used to enclose strings. A value wrapped in that character is read as one field even if it contains the delimiter, so "Smith, John" stays one customer name.
Other CSV options are useful, but none of them fixes a comma inside a value. NULL_IF lists strings to replace with NULL. TRIM_SPACE removes whitespace from fields. ESCAPE names an escape character. PARSE_HEADER = TRUE reads column names from the first row, which tells Snowflake nothing about quoting. ERROR_ON_COLUMN_COUNT_MISMATCH = FALSE only stops the parsing error raised when a row's field count does not match the target table. The error goes away, but the split name still pushes every later value into the wrong column.
Checkpoint 2 of 8· Check yourself
A team loads the same CSV layout from one named external stage into several tables. They are tired of repeating the parsing options in every COPY statement. What is the best approach?
CREATE FILE FORMAT creates a named, reusable format, and a named stage can hold the options that describe its staged files. Without options, Snowflake does not detect anything: it assumes a plain comma CSV. PARSE_HEADER only reads column names and says nothing about quoting.
“convenience settings such as the options that describe the format of staged files”Source: docs.snowflake.com
Checkpoint 3 of 8· Exam question
A partner drops a daily CSV into an external stage. The first line is a header row, and the customer name field is wrapped in double quotes because it can contain commas, such as "Smith, John". Which file format definition loads each row into the correct columns?
Correct answer: B — CREATE FILE FORMAT partner_csv TYPE = CSV SKIP_HEADER = 1 FIELD_OPTIONALLY_ENCLOSED_BY = '"' NULL_IF = ('');
- A. Changing the delimiter to a semicolon does not match the comma-delimited file, so every row would be read as a single field. Trimming spaces does nothing to keep quoted commas together.
- B. Skipping one header line and declaring the double quote as the optional enclosure keeps "Smith, John" as a single field. This is the standard CSV definition for a header row plus quoted values.
- C. Setting
SKIP_HEADER = 0loads the header line as a data row, which fails on numeric columns. Disabling the enclosure and using a backslash escape leaves the commas inside the quotes acting as delimiters. - D.
PARSE_HEADER = TRUEreads column names from the header but does not define an enclosure character, so quoted commas still split the name into two fields. Turning off the column-count check would then hide the resulting misaligned rows instead of fixing them.
3.Querying staged files before you load them
You can run SELECT directly against files on a stage. It is the quickest way to check that a file format parses a file the way you expect, before anything is written to a table. Fields are addressed by position: $1 is the first field, $2 the second, and so on. In a semi-structured file, $1:element reaches into the value. The FROM clause names the stage location, optionally with a path. It can also pass FILE_FORMAT => with a named file format and PATTERN => with a regular expression that picks which files to read.
SELECT t.$1, t.$2 FROM @mystage1 (file_format => 'myformat', pattern=>'.*data.*[.]csv.gz') t;You can leave out the file format only in two cases: the files use the default CSV delimiters, or the stage definition already carries the file format. Otherwise, Snowflake parses with the wrong format and gives no warning.
Staged queries also expose metadata pseudo-columns:
METADATA$FILENAMEis the name of the staged file the row came from, including its full path.METADATA$FILE_ROW_NUMBERis the row's number within that file.METADATA$FILE_CONTENT_KEY,METADATA$FILE_LAST_MODIFIEDandMETADATA$START_SCAN_TIMEgive the file's checksum, its last-modified time and the time the scan started.
These columns appear only when you name them. SELECT * does not return them, and neither do SHOW, DESCRIBE or INFORMATION_SCHEMA queries. Copying them into a table during a load is part of loading data with COPY INTO.
SELECT METADATA$FILENAME, METADATA$FILE_ROW_NUMBER, parse_json($1) FROM @mystage2/data1.json.gz;Staged queries are built for simple inspection and for transforming data during a load. They do not replace loading the data into a table and querying the table. Use them to check a file before you commit to a file format, not as the way analysts read the data every day.
Checkpoint 4 of 8· Check yourself
You run SELECT * FROM @mystage1 (file_format => 'myformat') and expect to see which file each row came from, but no file-name column appears. What should you do?
Metadata pseudo-columns exist on every staged file but are never part of SELECT *. SHOW, DESCRIBE and INFORMATION_SCHEMA queries leave them out as well, so the only way to see them is to write their names in the query.
“Metadata columns can only be queried by name”Source: docs.snowflake.com
4.Semi-structured formats and the VARIANT column
Snowflake imports semi-structured data from JSON, Avro, ORC, Parquet and XML. It stores that data in types built for hierarchies: OBJECT for key-value pairs, ARRAY for ordered lists, and VARIANT, which can hold a value of any type, including the other two. For JSON, Avro, ORC and Parquet, Snowflake builds the hierarchy for you once you name the format in TYPE. The usual pattern is a single VARIANT column plus a COPY with the right format type.
CREATE TABLE my_table (my_variant_column VARIANT); COPY INTO my_table ... FILE FORMAT = (TYPE = 'JSON') ...The formats look different on disk but end up the same once loaded:
- JSON is plain text, with objects in curly braces and arrays in square brackets.
- Avro is a compact binary format whose schema, written in JSON, travels with the data.
- ORC is a binary columnar format designed for Hive data.
Snowflake reads Avro and ORC into a single VARIANT column, and you query it the same way as JSON.
The limit you are most likely to hit is size. A VARIANT value can hold at most 128 MB of uncompressed data, and in practice a little less because of internal overhead. If a vendor exports 120 MB of orders as one top-level array, [ {…}, {…}, … ], the file is one value, and the load fails even though each order is small. The JSON file format option for this case is STRIP_OUTER_ARRAY = TRUE. It handles files that hold a JSON array at the top level by removing the outer brackets, so each element of the array loads as its own row.
No file format option raises the 128 MB ceiling, so the fix has to deal with the outer array itself. STRIP_NULL_VALUES removes object or array elements that contain null values. That can trim a few bytes, but the orders still sit inside one array. Reading the file as CSV just moves the same oversized content into a single text field.
XML has its own options. Its file format offers STRIP_OUTER_ELEMENT, which removes the outer XML element and exposes the second-level elements as separate documents. This is the XML counterpart of removing an outer JSON array. To retrieve a child element of an XML value by its tag name, for example <customer> from a VARIANT column called doc, use the XMLGET function. Casting and flattening these values into columns is covered in preparing semi-structured data.
Checkpoint 5 of 8· Check yourself
Avro files from a Hadoop pipeline land on an external stage, and analysts want to query them with the same path syntax they use for JSON. Which load design fits with the least upfront work?
For JSON, Avro, ORC and Parquet, naming the format in TYPE is enough. Snowflake reads the data into a single VARIANT column, and you query that column the same way as JSON. You don't need to declare columns in advance or convert the files first, and XMLGET is only for XML values.
“Snowflake reads Avro data into a single VARIANT column. You can query the data in a VARIANT column just as you would JSON data”Source: docs.snowflake.com
Checkpoint 6 of 8· Exam question
A vendor exports a 120 MB JSON file that holds a single top-level array of order objects. A COPY INTO into a table with one VARIANT column fails because the value exceeds the maximum size of a VARIANT. What change to the load fixes this so that every order becomes its own row?
Correct answer: C — Set STRIP_OUTER_ARRAY = TRUE on the JSON file format so each element of the outer array is loaded as a separate row.
- A.
ALLOW_DUPLICATEonly permits repeated object keys. It does not raise the VARIANT size limit or split the array. - B.
STRIP_NULL_VALUESremoves object fields with null values and cannot reduce 120 MB of order data below the limit; the array would still be one value. - C.
STRIP_OUTER_ARRAY = TRUEremoves the outer brackets so each order object becomes a separate row. That keeps every VARIANT value small and solves the size error. - D. Reading the file as CSV with an unused delimiter still produces one giant field per line, which would exceed field-size limits and loses the JSON structure that VARIANT provides.
Checkpoint 7 of 8· Exam question
An analyst loads XML documents into a VARIANT column named doc and needs to pull out the child element <customer> from each record. Which function retrieves a child element of an XML value by its tag name?
Correct answer: B — XMLGET
- A.
PARSE_XMLconverts a string into an XML-typed VARIANT. It does not pick a child element from a value that is already parsed. - B.
XMLGETreturns the child element with the given tag name from an XML value, for exampleXMLGET(doc, 'customer'), and reads the content with:"$". - C.
CHECK_XMLonly validates whether text is well-formed XML and returns an error message or NULL, so it extracts nothing. - D.
STRIP_NULL_VALUEconverts JSON null in a VARIANT to SQL NULL and has no concept of XML tags.
5.Unstructured files: directory tables and file URLs
Snowflake does not parse unstructured files into rows. Retrieving them means two steps: finding the files, then giving people a way to open them. Both internal and external stages can hold unstructured files. A directory table handles the finding. It is an implicit object layered on a stage, not a separate database object, and it stores file-level metadata. You add one with DIRECTORY = (ENABLE = TRUE) on CREATE STAGE, or later with ALTER STAGE … SET DIRECTORY.
SELECT FILE_URL FROM DIRECTORY(@mystage) WHERE RELATIVE_PATH LIKE '%.csv';DIRECTORY(@stage) returns one row per file, with RELATIVE_PATH, SIZE, LAST_MODIFIED, MD5, ETAG and FILE_URL. On an internal stage, you refresh the metadata manually with ALTER STAGE … REFRESH after files change. On an external stage, the refresh can run automatically from your cloud provider's event notifications. If you join the directory table to a table of facts about the documents, such as author or publish date, one view shows each file next to its data.
For opening the files, Snowflake has three URL types. They differ in who can open the file and for how long.
| URL type | How to generate | Who can open the file | Expires | Usable by consumers through a shared secure view |
|---|---|---|---|---|
| Scoped URL | BUILD_SCOPED_FILE_URL | Only the user who generated the URL | When the query results cache expires (currently 24 hours) | Yes |
| File URL | Directory table FILE_URL column, or BUILD_STAGE_FILE_URL | A role with USAGE (external stage) or READ (internal stage) on the stage, sending a GET request with an authorization token | Permanent | No |
| Pre-signed URL | GET_PRESIGNED_URL | Anyone who has the URL, with no Snowflake login | After the time set in expiration_time | Yes |
The sharing column follows from what each URL needs in order to work. A file URL grants nothing by itself: the request succeeds only when the role making it holds USAGE (external stage) or READ (internal stage) on the stage. A consumer account's roles hold no such privilege on the provider's stage, so a file URL returned by a shared secure view fails for the consumer. A scoped URL carries its own temporary access without granting privileges on the stage, and a pre-signed URL carries its access in the token, which is why both survive a share.
Pick the URL type by who needs the file:
- Scoped URL: suits a file administrator who exposes files through a view. Only roles with privileges on the view see the URLs, each URL works only for the user who generated it, and query history records who opened which file and when.
- File URL: permanent, so it suits a custom application that already authenticates against the REST API. Data consumers cannot use file URLs in a shared secure view.
- Pre-signed URL: open to anyone who holds it until the token expires. That suits a BI or reporting tool that only needs to display a document, and it is the reason a pre-signed URL should never go into a channel you do not control.
Internal stages need one decision when you create them. Files on an internal stage are client-side encrypted by default, and client-side encrypted files cannot be read through pre-signed, file or scoped URLs. If people will open the files through URLs, consider server-side encryption when you create the stage.
Checkpoint 8 of 8· Check yourself
Your company shares a secure view with a partner account so the partner can open PDF contracts on an internal stage. Each link must work only for the person who queried the view, not for anyone it is forwarded to. Which URL type should the view return?
Data consumers can open scoped URLs through a shared secure view, and only the user who generated a scoped URL can use it. Consumers cannot open file URLs through a provider's secure view. A pre-signed URL works in a share, but anyone who has it can open the file until it expires.
“Ideal for use in custom applications, for providing unstructured data to other accounts through a share”Source: docs.snowflake.com
Sources
(13)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Structured data (such as a CSV file) follows a strict tabular schema.”
↩︎ Three categories of source data“Unstructured data (such as a document, image, or audio file) has no inherent schema.”
↩︎ Three categories of source data - 2.
“Semi-structured data does not require a prior definition of a schema and can constantly evolve”
↩︎ Three categories of source data“Snowflake can import semi-structured data from JSON, Avro, ORC, Parquet, and XML formats”
↩︎ Semi-structured formats and the VARIANT column“For information about querying XML by specifying XML tags, see the documentation of the XMLGET function.”
↩︎ Semi-structured formats and the VARIANT column“Snowflake can build the hierarchy for you and store it in a VARIANT.”
↩︎ Checkpoint - 3.
“You cannot access data held in archival cloud storage classes that requires restoration before it can be retrieved.”
↩︎ Three categories of source data“Snowflake refers to the location of data files in cloud storage as a stage.”
↩︎ Key concept“convenience settings such as the options that describe the format of staged files”
↩︎ Checkpoint - 4.
“The default file format is character-delimited UTF-8 text (that is, CSV), with the comma character (,) as the field delimiter”
↩︎ Describing a CSV file with a file format“Specifies the positional number of the field/column (in the file) that contains the data to be loaded”
↩︎ Querying staged files before you load them“is not intended to replace loading data into tables and performing queries on the tables.”
↩︎ Querying staged files before you load them“In the second query, the file format is omitted, causing the | field delimiter to be ignored”
↩︎ Prediction - 5.
“Number of lines skipped at the start of the file.”
↩︎ Describing a CSV file with a file format“Whether to generate a parsing error if the number of fields in an input file does not match the number of columns”
↩︎ Describing a CSV file with a file format“Character used to enclose strings.”
↩︎ Exam trap 1 - 6.https://docs.snowflake.com/en/developer-guide/snowpark-connect/snowpark-connect-file-ioOfficial docs
“uses column names from the first row”
↩︎ Describing a CSV file with a file format“When true, the reader handles files that contain a JSON array at the top level or span multiple lines.”
↩︎ Semi-structured formats and the VARIANT column - 7.
“Name of the staged data file the current row belongs to. Includes the full path to the data file.”
↩︎ Querying staged files before you load them“Metadata columns can only be queried by name”
↩︎ Exam trap 2“Metadata columns can only be queried by name”
↩︎ Checkpoint - 8.
“Snowflake reads Avro data into a single VARIANT column.”
↩︎ Semi-structured formats and the VARIANT column“Snowflake reads Avro data into a single VARIANT column. You can query the data in a VARIANT column just as you would JSON data”
↩︎ Checkpoint - 9.
“A VARIANT value can have a maximum size of up to 128 MB of uncompressed data.”
↩︎ Semi-structured formats and the VARIANT column“This option removes OBJECT elements or ARRAY elements containing”
↩︎ Semi-structured formats and the VARIANT column - 10.
“Boolean that specifies whether the XML parser strips out the outer XML element, exposing 2nd level elements as separate documents.”
↩︎ Semi-structured formats and the VARIANT column - 11.
“A directory table is an implicit object layered on a stage (not a separate database object)”
↩︎ Unstructured files: directory tables and file URLs - 12.
“Directory tables on internal stages require manual metadata refreshes.”
↩︎ Unstructured files: directory tables and file URLs - 13.
“Only the user who generates a scoped URL can use the URL to access the referenced file.”
↩︎ Unstructured files: directory tables and file URLs“Any person who has the pre-signed URL can access the referenced file for the life of the token.”
↩︎ Unstructured files: directory tables and file URLs“client-side encrypted files are unreadable by users and external tools using pre-signed, file, or scoped URLs.”
↩︎ Unstructured files: directory tables and file URLs“A role that has sufficient privileges on the stage can access the files.”
↩︎ Unstructured files: directory tables and file URLs“Encoded URL that permits temporary access to a staged file without granting privileges to the stage.”
↩︎ Unstructured files: directory tables and file URLs“Role specified in the GET REST API call must have sufficient privileges on the stage: USAGE (external stage) or READ (internal stage).”
↩︎ Unstructured files: directory tables and file URLs“Unstructured data files cannot be accessed by data consumers via column values of this type in secure views shared by data providers.”
↩︎ Exam trap 3“Ideal for use in custom applications, for providing unstructured data to other accounts through a share”
↩︎ Checkpoint