3: Data Loading, Unloading, and Connectivity

    Perform data loading and unloading

    How it works

    Data loading into Snowflake is a two-step model: files land in a stage, then a load command moves their contents into tables.

    This separation lets the same files satisfy multiple targets, lets the file format be defined once and reused, and lets the workload run on a virtual warehouse sized for the file count and size.

    Data unloading reverses the flow: query output is written to a stage as one or more files, governed by the same file-format and copy options.

    Choosing the wrong stage type, the wrong file format option, or the wrong on-error policy is the single largest source of failed loads in practice and the most heavily tested area in this domain.

    When the input is a tabular extract from another system, the natural answer is a delimited or columnar file (CSV, Parquet, ORC).

    When the input arrives as nested API payloads, the format is JSON, Avro, or XML, and Snowflake's VARIANT type holds the parsed document.

    When the input is binary content with no row structure (PDFs, images, audio), the file is registered in a directory table and processed through unstructured-data functions.

    Each path requires a stage to act as the addressable file location and a copy operation to materialize rows in the destination table.

    File formats

    A file format is a named, schema-scoped object that captures the parsing rules for a file type: delimiter, header behavior, compression codec, null markers, escape characters, date formats, and per-format options like STRIP_OUTER_ARRAY for JSON or BINARY_AS_TEXT for Parquet. Snowflake supports CSV (delimited text), JSON, Avro, ORC, Parquet, and XML.

    A file format can be defined inline in a COPY statement or as a persistent object referenced by name. Persistent file formats are the standard pattern because they centralize the parsing contract: if the upstream changes its delimiter, one ALTER FILE FORMAT statement updates every load that references it.

    CREATE OR REPLACE FILE FORMAT raw_db.landing.ff_csv_pipe
     TYPE = CSV
     FIELD_DELIMITER = '|'
     SKIP_HEADER = 1
     NULL_IF = ('NULL', '')
     EMPTY_FIELD_AS_NULL = TRUE
     COMPRESSION = AUTO
     FIELD_OPTIONALLY_ENCLOSED_BY = '"'
     ESCAPE_UNENCLOSED_FIELD = NONE
     DATE_FORMAT = 'YYYY-MM-DD'
     TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS.FF3';
    
    CREATE OR REPLACE FILE FORMAT raw_db.landing.ff_json_array
     TYPE = JSON
     STRIP_OUTER_ARRAY = TRUE
     COMPRESSION = AUTO;
    
    CREATE OR REPLACE FILE FORMAT raw_db.landing.ff_parquet
     TYPE = PARQUET
     BINARY_AS_TEXT = FALSE
     USE_LOGICAL_TYPE = TRUE;
    

    The CSV format options have asymmetric defaults that catch new users.

    SKIP_HEADER defaults to 0; if a header row is present and SKIP_HEADER is not set, the header becomes data and may fail the load when it does not match the target schema.

    FIELD_OPTIONALLY_ENCLOSED_BY defaults to NONE; a CSV produced with quoted strings will then carry the quote characters into the loaded values.

    EMPTY_FIELD_AS_NULL defaults to TRUE for CSV, which means an empty || is loaded as NULL, not as an empty string.

    JSON formats default STRIP_OUTER_ARRAY = FALSE, so a file containing [ {...}, {...} ] loads as one VARIANT row containing the entire array unless the option is enabled.

    πŸ’‘ Exam Trap: CSV FIELD_DELIMITER and RECORD_DELIMITER accept a single character or a hex/octal sequence, not arbitrary strings. A tab delimiter is '\t'. A NUL byte delimiter is '\x00'. Setting both to the same character fails at parse time.

    πŸ’‘ Exam Trap: PARQUET and ORC are columnar formats; the COPY into a table from a Parquet file uses a column projection by name via MATCH_BY_COLUMN_NAME = CASE_SENSITIVE | CASE_INSENSITIVE. Without this option, the entire file row arrives as a single VARIANT column ($1), which is the source of many "the data is in one column" support tickets.

    πŸ“Š Limit: A single COPY INTO command can reference exactly one file format. Files with mixed formats in the same stage path require multiple COPY commands.

    Create and use stages

    A stage is a file location addressed by Snowflake, used both as the source for COPY INTO <table> and as the destination for COPY INTO <location>.

    Snowflake distinguishes:

    • user stages (@~)
    • table stages (@%<table_name>)
    • named stages (@<stage_name>)

    Named stages are schema-scoped objects; user stages and table stages are implicit and cannot be customized.

    A named stage can be internal (storage owned and managed by Snowflake) or external (storage owned by the customer in AWS S3, Azure Blob Storage, or Google Cloud Storage).

    CREATE OR REPLACE STAGE raw_db.landing.int_stage_csv
     FILE_FORMAT = (FORMAT_NAME = raw_db.landing.ff_csv_pipe)
     DIRECTORY = (ENABLE = TRUE)
     COMMENT = 'Internal landing zone for delimited extracts';
    
    PUT file:///local/path/orders_2026q1.csv.gz @raw_db.landing.int_stage_csv
     PARALLEL = 8
     AUTO_COMPRESS = FALSE;
    
    LIST @raw_db.landing.int_stage_csv;
    
    • The PUT command moves a file from a client filesystem into an internal stage.
    • GET retrieves a staged file back to the client.

    Both commands require a client driver that supports them: SnowSQL, the Snowflake CLI, and the Python Snowflake Connector all support PUT and GET, but Snowsight worksheets, drivers like JDBC and ODBC, and the Snowpark sessions support file operations through dedicated APIs rather than the SQL PUT statement directly.

    Internal stages

    There are three internal stage types.

    • A user stage is automatically created for every user as @~; it is private to the user and survives across sessions but is not visible to other users.
    • A table stage is automatically created for every table as @%<table_name>; it is owned by the table and is read by COPY INTO without specifying the format options inline.
    • A named internal stage is an explicit object created with CREATE STAGE.

    Only named internal stages support custom file format defaults, directory tables, encryption settings, and granular grants. The selection rule is mechanical:

    • use a user stage for ad hoc uploads by one user
    • use a table stage for files that target exactly one table
    • use a named internal stage when multiple users or processes share the location or when the stage drives Snowpipe or directory-table workflows.

    Internal stages encrypt data at rest using a key managed by Snowflake; files are also encrypted client-side by SnowSQL and the connectors before they reach the cloud provider's blob service, providing dual-layer protection.

    ⚠️ Anti-Pattern: Using the user stage @~ as a long-lived shared landing zone. The user stage is private to one user, has no directory table, cannot be granted, and is purged when the user is dropped. Production pipelines must use a named internal stage with explicit grants.

    External stages

    An external stage points to a cloud storage URL: s3://bucket/prefix/, azure://account.blob.core.windows.net/container/prefix/, or gcs://bucket/prefix/. External stages do not store data; they store metadata (URL, credentials or integration, file format default, encryption settings, directory table). The credentials may be inline (an access key pair) or, the standard, a storage integration object that lets Snowflake assume an IAM role in the cloud account.

    CREATE OR REPLACE STAGE raw_db.landing.ext_stage_s3
     URL = 's3://acme-data-lake/raw/orders/'
     STORAGE_INTEGRATION = s3_landing_int
     FILE_FORMAT = (FORMAT_NAME = raw_db.landing.ff_parquet)
     DIRECTORY = (ENABLE = TRUE, AUTO_REFRESH = TRUE)
     COMMENT = 'S3 landing for Parquet extracts';
    
    LIST @raw_db.landing.ext_stage_s3 PATTERN = '.*\\.parquet';
    

    External stages support large-file egress and ingest patterns: a producer writes Parquet to S3, Snowflake reads it without copying. They also support partition-style URL pruning when the file path encodes Hive-style partitions and the COPY references those segments via metadata$filename. For unstructured data, external stages with directory tables provide presigned URLs for downstream consumers.

    πŸ’‘ Exam Trap: The cross-cloud-region cost model differs for stages. Reading from an external stage in the same cloud region as the Snowflake account incurs no egress; reading from a different region or different cloud provider incurs egress at the source cloud's published rates. Loading from a cross-region S3 bucket is supported but is the most expensive ingest path.

    Server-side encryption

    Files in an external stage can be encrypted using one of three server-side encryption modes set on the stage at creation time.

    • SNOWFLAKE_FULL (the default for internal stages) encrypts client-side then server-side using a Snowflake-managed key.
    • SNOWFLAKE_SSE uses server-side encryption only with a Snowflake-managed key, suitable when files are produced by external tools that cannot perform client-side encryption.

    For external stages, the relevant settings are TYPE = 'AWS_SSE_KMS' | 'AWS_SSE_S3' | 'AZURE_CSE' | 'GCS_SSE_KMS', paired with a KMS_KEY_ID for KMS-managed paths.

    CREATE OR REPLACE STAGE raw_db.landing.ext_stage_kms
     URL = 's3://acme-data-lake/confidential/'
     STORAGE_INTEGRATION = s3_landing_int
     ENCRYPTION = (TYPE = 'AWS_SSE_KMS' KMS_KEY_ID = 'arn:aws:kms:us-east-1:123456789012:key/abcd-1234')
     FILE_FORMAT = (FORMAT_NAME = raw_db.landing.ff_parquet);
    

    The IAM role used by the storage integration must have kms:Decrypt (for read) and kms:Encrypt, kms:GenerateDataKey (for write) on the referenced KMS key. Misconfigured KMS permissions surface as opaque "access denied" errors at COPY time even though LIST @stage succeeds, because LIST only requires s3:ListBucket while reading the object requires KMS decryption.

    πŸ“Š Limit: Internal stages always use Snowflake-managed AES-256 encryption and cannot be reconfigured to use a customer KMS key directly. To pin ingest data to a customer key, the customer must store source files in an external stage on customer-controlled storage and rely on Tri-Secret Secure (Business Critical edition or higher) for storage-layer key protection.

    Directory tables

    A directory table is a metadata layer over the files in a stage.

    When enabled with DIRECTORY = (ENABLE = TRUE), the stage exposes a virtual table queryable via SELECT * FROM DIRECTORY(@stage) that lists each file's relative path, size, last modified timestamp, MD5, and a built-in pre-signed URL function.

    Directory tables support AUTO_REFRESH = TRUE, which subscribes the metadata to cloud-event notifications (S3 Event Notification, Azure Event Grid, GCS Pub/Sub) so additions and removals are reflected without manual refresh.

    Manual refresh uses ALTER STAGE <name> REFRESH.

    Directory tables are the primary mechanism for cataloging unstructured data: PDFs, images, audio.

    Combined with Cortex AI SQL functions (introduced in Chapter 1), a directory table over a stage of PDFs lets the user call SNOWFLAKE.CORTEX.PARSE_DOCUMENT row by row to extract text.

    They also expose file URLs for sharing through Streamlit applications.

    -- Query metadata for files staged for ingest
    SELECT
     RELATIVE_PATH,
     SIZE,
     LAST_MODIFIED,
     MD5,
     ETAG,
     BUILD_SCOPED_FILE_URL(@raw_db.landing.ext_stage_s3, RELATIVE_PATH) AS scoped_url
    FROM DIRECTORY(@raw_db.landing.ext_stage_s3)
    WHERE RELATIVE_PATH ILIKE '%.parquet';
    

    πŸ’‘ Exam Trap: A directory table does NOT load file contents into Snowflake. It indexes only file metadata. To read file contents, the workload still uses COPY INTO (for structured data) or a function like TO_FILE and SNOWFLAKE.CORTEX.PARSE_DOCUMENT (for unstructured data).

    COPY INTO command

    The COPY INTO command exists in two directions: COPY INTO <table> FROM <stage> for loading, and COPY INTO <stage> FROM (<query>) for unloading.

    The loading variant:

    • scans the stage
    • identifies new files via the load metadata (a per-table list of files already loaded)
    • applies the file format
    • transforms columns via the SELECT clause if used
    • writes rows

    The unloading variant:

    • runs the query
    • partitions output across files according to the file size targets
    • writes files to the destination stage
    -- Basic load with on-error policy and file pattern
    COPY INTO raw_db.landing.orders_raw (order_id, customer_id, order_ts, amount)
     FROM @raw_db.landing.ext_stage_s3
     FILE_FORMAT = (FORMAT_NAME = raw_db.landing.ff_parquet)
     PATTERN = '.*orders_2026.*\\.parquet'
     MATCH_BY_COLUMN_NAME = CASE_INSENSITIVE
     ON_ERROR = 'ABORT_STATEMENT'
     PURGE = FALSE
     FORCE = FALSE
     RETURN_FAILED_ONLY = FALSE
     LOAD_UNCERTAIN_FILES = FALSE;
    
    -- Load with column transformation from CSV
    COPY INTO raw_db.landing.orders_raw (order_id, customer_id, order_ts, amount)
     FROM (
     SELECT
     $1::NUMBER AS order_id,
     $2::NUMBER AS customer_id,
     $3::TIMESTAMP_NTZ AS order_ts,
     $4::NUMBER(18,2) AS amount
     FROM @raw_db.landing.int_stage_csv
     )
     FILE_FORMAT = (FORMAT_NAME = raw_db.landing.ff_csv_pipe);
    

    The MATCH_BY_COLUMN_NAME option is the standard pattern for columnar formats (Parquet, ORC) and self-describing formats (Avro, JSON with target table).

    For CSV, columns are referenced positionally as $1, $2 in the SELECT projection.

    The PATTERN argument applies a regex to the staged file list. The FILES argument names files explicitly.

    Specifying explicit files is faster on large stages because the engine skips the directory listing for non-matching files. Snowflake tracks load history per table for 64 days.

    Within that window, a file already loaded into a table is skipped on subsequent COPY runs even if the file content changed, unless FORCE = TRUE is set.

    After 64 days, the load metadata for that file expires, and the file may be loaded again if it still exists in the stage.

    The LOAD_UNCERTAIN_FILES option overrides the safety check that suppresses loads when load history is partially missing.

    -- Unload a query result to a stage as gzipped Parquet
    COPY INTO @raw_db.landing.int_stage_csv/exports/orders_summary/
     FROM (
     SELECT customer_id, COUNT(*) AS order_count, SUM(amount) AS amount_total
     FROM raw_db.landing.orders_raw
     GROUP BY customer_id
     )
     FILE_FORMAT = (TYPE = PARQUET COMPRESSION = SNAPPY)
     HEADER = TRUE
     MAX_FILE_SIZE = 268435456
     OVERWRITE = TRUE
     SINGLE = FALSE
     INCLUDE_QUERY_ID = TRUE;
    

    For unloads, MAX_FILE_SIZE defaults to 16 MB and accepts up to 5 GB. SINGLE = TRUE writes one file but disables parallelism; the larger MAX_FILE_SIZE plus SINGLE = FALSE is the higher-throughput choice. INCLUDE_QUERY_ID = TRUE appends the query ID to each output filename, providing a unique suffix that survives re-runs.

    πŸ“Š Limit: A single COPY INTO <location> (unload) command produces files no larger than 5 GB per file. To export a single very large dataset, allow Snowflake to split into many files (the default) and concatenate downstream if required.

    πŸ’‘ Exam Trap: PURGE = TRUE deletes files from the stage after a successful load. If the COPY fails partway, no files are purged. If the COPY succeeds but the COMMIT later fails (rare, but possible in a multi-statement transaction), files are still purged. Use PURGE = FALSE plus a separate REMOVE @stage step in a Task when you need transactional safety.

    Error handling options

    The ON_ERROR option controls how COPY INTO behaves when a row fails to parse or fails type coercion. Five values are accepted:

    • ABORT_STATEMENT (default for COPY INTO <table>): on the first error in any file, abort the whole statement and load no rows.
    • CONTINUE: skip the failing row, continue with the file, continue with remaining files.
    • SKIP_FILE: on the first error in a file, abandon that file (no rows from that file loaded), continue with the next file.
    • SKIP_FILE_<num>: abandon the file after num errors.
    • SKIP_FILE_<num>%: abandon the file after errors exceed num percent of rows.

    The error metadata is queryable via VALIDATION_MODE = 'RETURN_ERRORS' or by reading INFORMATION_SCHEMA.LOAD_HISTORY and the per-load RESULT_SCAN of the COPY query ID. For automated remediation, the standard pattern is to run COPY with ON_ERROR = 'CONTINUE' and RETURN_FAILED_ONLY = TRUE, capture the result set, write failed rows into a quarantine table for later inspection, then reprocess.

    -- Validate without loading to discover format issues
    COPY INTO raw_db.landing.orders_raw
     FROM @raw_db.landing.ext_stage_s3
     FILE_FORMAT = (FORMAT_NAME = raw_db.landing.ff_parquet)
     VALIDATION_MODE = 'RETURN_5_ROWS';
    
    COPY INTO raw_db.landing.orders_raw
     FROM @raw_db.landing.ext_stage_s3
     FILE_FORMAT = (FORMAT_NAME = raw_db.landing.ff_parquet)
     VALIDATION_MODE = 'RETURN_ERRORS';
    

    VALIDATION_MODE is a pre-flight check. RETURN_n_ROWS returns the first n rows that would be loaded, RETURN_ERRORS returns only the errors. No rows are written to the target table while validation runs, regardless of the on-error policy.

    Load planning: warehouse and file sizing

    The published guidance is to load files of 100-250 MB compressed for best throughput.

    Very small files (under a few megabytes) waste per-file overhead. Very large files (several GB) reduce parallelism because each file is processed by a single thread on a warehouse server.

    An X-Small warehouse has 8 threads (one node x 8 cores). Each doubled size adds eight more threads.

    Sizing a warehouse so that thread count is at least the file count keeps every thread occupied without leaving compute idle.

    For one-off backloads of millions of small files, a Medium or Large warehouse is usually right. For steady-state ingest, an X-Small with Snowpipe is cheaper than a manually invoked larger warehouse.

    🎯 Scenario: An analytics team ingests a daily 9 GB Parquet export by running COPY INTO orders FROM @ext_stage on a Large warehouse. Wall time is 22 minutes; the warehouse sits at 12% utilization. Investigation shows the export is one file. Splitting the producer to write 60 files of 150 MB each cuts wall time to 2 minutes on an X-Small warehouse because every thread has work; total credit consumption drops by a factor of 50.

    Decision Anchor: stage selection

    When to use

    • Choose a user stage (@~) when one user uploads files for personal analysis and the files do not need to be shared.
    • Choose a table stage (@%table) when files map to exactly one table and the schema's grant model on tables is sufficient.
    • Choose a named internal stage when multiple users share an upload landing area, when a directory table is required, when Snowpipe or Tasks reference the stage, or when granular grants on the stage are required.
    • Choose an external stage when files are produced outside Snowflake, when the upstream cannot use PUT, when files must be reachable by non-Snowflake consumers, or when storage cost on customer-controlled blob storage is preferable to Snowflake-managed storage.

    Visualizing the load flow

    Load Flow: Files to Snowflake Table

    ⚠️ Anti-Pattern: Loading thousands of 1 KB files with ON_ERROR = 'CONTINUE'. Per-file metadata overhead dominates wall time; small files should be concatenated upstream before load, or routed through Snowpipe Streaming instead.

    πŸ’‘ Exam Trap: The load history dedupe window is 64 days. Files older than 64 days that still exist in the stage are eligible for reload. Production pipelines should PURGE = TRUE after successful load or use stage lifecycle rules to age out files before the 64-day window closes; otherwise a future archive replay can double-load.

    πŸ“Š Limit: A COPY INTO <table> statement can have at most a 1 GB total error result set returned to the client. If more errors are present, the query returns a truncation indicator and the user must query LOAD_HISTORY to read the rest.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Snowflake - SnowPro Core learning hub.