What you will be able to do
- Write a COPY INTO command that loads a table from any stage type, choosing files with FILES or PATTERN
- Explain how load metadata stops duplicate loads, and when FORCE or LOAD_UNCERTAIN_FILES overrides it
- Choose the ON_ERROR value that matches a stated tolerance for bad rows or files
- Validate files before a load with VALIDATION_MODE and inspect errors after one with VALIDATE()
- Unload table or query results to a stage with COPY INTO
1.Loading staged files into a table with COPY INTO
COPY INTO <table> is the bulk load command. It reads files that are already staged and inserts them into a table that already exists. The FROM clause can name a named internal stage (@stage), a table stage (@%table), the user stage (@~), a named external stage, or a raw cloud URL such as 's3://bucket/path' with its own credentials. That last form uses the same STORAGE_INTEGRATION, CREDENTIALS and ENCRYPTION parameters as an external stage. The FROM value must be a literal, not a SQL variable. Bulk loads run on a virtual warehouse that you provide, and you are responsible for sizing it for the load.
COPY INTO mytable
FROM @my_int_stage/sales/
FILE_FORMAT = (FORMAT_NAME = my_csv_format)
PATTERN = '.*sales.*[.]csv'
ON_ERROR = 'SKIP_FILE';Three things decide which files a COPY picks up. A path after the stage name is treated as a case-sensitive prefix. Snowflake matches it against file names, so /./ and /../ are taken literally rather than resolved. FILES = ('a.csv', 'b.csv') lists exact names. PATTERN = '<regex>' selects files by regular expression. Format comes from FILE_FORMAT, either FORMAT_NAME pointing at a named object or an inline TYPE with options.
A COPY can also transform rows on the way in. Using SELECT $1, $2 ... FROM @stage as the source, you can reorder columns, leave some out, cast values and truncate strings that are too long. The files do not need the same number or order of columns as the table. Table stages are the exception: they cannot be the source of a transforming COPY, so a load that needs a SELECT has to read from a named stage or the user stage.
Checkpoint 1 of 5· Check yourself
CSV files for the ORDERS table were uploaded with PUT to @%orders. The columns in the files are in a different order from the table, and one column has to be cast during the load. What should you do?
You can't use a table stage as the source of a COPY that runs a SELECT. To reorder columns or cast values during the load, the files must come from a named stage or the user stage.
“Table stages don't support transforming data while loading it (using a query as the source for the COPY command).”Source: docs.snowflake.com
2.Load metadata: why a file is not loaded twice
Each table keeps load metadata that records which files have been loaded into it. A file already in that record is skipped on later COPY runs, so you can rerun a COPY over a stage that still holds yesterday's files without duplicating rows. The metadata lasts 64 days.
Older files are the hard case. Suppose a file's LAST_MODIFIED date is more than 64 days old, and the table's initial load was also more than 64 days ago. COPY can no longer tell whether the file was loaded. It errs on the side of caution and skips the file by default, to avoid an accidental reload. You can override that in two ways:
LOAD_UNCERTAIN_FILES = TRUEstill uses the load metadata where it exists, so it avoids duplicates, but it also tries files whose metadata has expired.FORCE = TRUEignores load metadata completely and loads every file. That can reload files and duplicate data in the table.
Load history expires along with this metadata. The VALIDATE() function, covered in the next section, fails once the copy history metadata for the load it is asked about has expired.
Checkpoint 2 of 5· Fill the gap
A nightly COPY skips a batch of staged files that were last modified more than 64 days ago. The table's first load was also more than 64 days ago. You want those files loaded, but no file that the remaining load metadata shows as already loaded should be loaded again. Which copy option should you set to TRUE?
? = TRUE | FALSELOAD_UNCERTAIN_FILES still uses load metadata where it exists, so it avoids duplicates, and it also tries the files whose metadata has expired. FORCE ignores load metadata entirely and can reload files, which duplicates rows. PURGE has nothing to do with deciding which files get loaded.
Source: docs.snowflake.com3.ON_ERROR, VALIDATION_MODE and VALIDATE()
ON_ERROR sets what a load does when it hits a bad row. The default, ABORT_STATEMENT, stops the whole COPY at the first error. That suits loads where partial data is worse than no data. The other values let the load continue, at different levels of detail:
| Value | Effect when a file contains an error row | When it fits |
|---|---|---|
| ABORT_STATEMENT (default) | The whole COPY statement stops | All-or-nothing batches |
| CONTINUE | Keeps loading that file; only the error rows are left out | Large files with no logical boundaries, where a few bad rows are acceptable |
| SKIP_FILE | Skips the entire file and loads the other files | Each file is a unit that must load completely or not at all |
| SKIP_FILE_<num> | Skips the file once its error rows reach the number given | Tolerating a small, fixed number of bad rows per file |
| 'SKIP_FILE_<num>%' | Skips the file once its error rows reach the percentage given | Tolerance that scales with file size |
The difference between CONTINUE and SKIP_FILE is about what happens to the bad file. With CONTINUE, the good rows of that file are loaded, so the table ends up with part of it. With SKIP_FILE, none of it is loaded, and every other file loads in full. The threshold forms only skip a file once a number or percentage of its rows have failed, and below the threshold they load the valid rows. SKIP_FILE also has a cost. It buffers every file whether or not it has errors, so it is slower than the other two. On large, arbitrarily cut files, skipping a whole file for one bad row wastes credits.
CONTINUE reports at most one error per file, so to see every error you need one of two validation tools. Run VALIDATION_MODE before the load. It checks the files and returns the errors (RETURN_ERRORS, RETURN_ALL_ERRORS) or sample rows (RETURN_<n>_ROWS) without loading anything:
COPY INTO mytable VALIDATION_MODE = 'RETURN_ERRORS';Run VALIDATE() after a load. It takes a COPY job and returns every error from that load, not just the first. Pass the query ID from Query History, or '_last' for the last load in the current session. It returns nothing if the load ran with ON_ERROR = ABORT_STATEMENT. It fails if the COPY transformed data with a SELECT, or if the copy history has expired.
VALIDATE( [<namespace>.]<table_name> , JOB_ID => { '<query_id>' | '_last' } )Checkpoint 3 of 5· Fill the gap
Before tonight's load runs, you want a list of every error in the staged files, and nothing may be written to the table yet. Which parameter of the table-loading COPY INTO completes this syntax line?
[ ? = RETURN_<n>_ROWS | RETURN_ERRORS | RETURN_ALL_ERRORS ]VALIDATION_MODE checks the staged files and returns errors or sample rows without loading anything, so it runs before the load. VALIDATE() is a function you call after a load, and it returns nothing for a load that ran with the default ABORT_STATEMENT. ON_ERROR = CONTINUE loads data and reports at most one error per file.
Source: docs.snowflake.comCheckpoint 4 of 5· Exam question
A COPY INTO statement fails partway through loading a batch of 50 CSV files because one file contains a row with a data type mismatch. The engineer wants the load to skip only that one problem file, load every other file completely, and continue processing without stopping the statement. Which ON_ERROR value should be set on the COPY command?
Correct answer: A — SKIP_FILE, which discards the entire file containing an error and proceeds to load the remaining files in the batch
- A. This option discards the whole file the moment any error is found in it and moves on to the next file, which matches the requirement to skip only the problem file while still loading every other file in full.
- B. This option loads the good rows from every file, including partial rows from the bad file, which is not what was asked since the requirement was to skip that entire file rather than partially load it.
- C. This is indeed the bulk-load default and it does halt the statement on the first error, which is the opposite of the requirement to keep processing the remaining 49 files.
- D. This threshold variant only discards a file once its error rate crosses the given percentage, so rows in a lightly-affected bad file would still be partially loaded instead of the file being skipped outright.
4.Unloading table data to files with COPY INTO
Unloading is the same command pointed the other way. COPY INTO <location> writes a table, or the result of any query, to one or more files. The target can be a named internal stage, a table or user stage, a named external stage, or a raw S3, GCS or Azure URL. Files unloaded to an internal stage can then be downloaded with GET.
COPY INTO { internalStage | externalStage | externalLocation }
FROM { [<namespace>.]<table_name> | ( <query> ) }
[ PARTITION BY <expr> ]
[ FILE_FORMAT = ( { FORMAT_NAME = '[<namespace>.]<file_format_name>' |
TYPE = { CSV | JSON | PARQUET } [ formatTypeOptions ] } ) ]
[ copyOptions ]
[ VALIDATION_MODE = RETURN_ROWS ]
[ HEADER ]The syntax gives away the asymmetry with loading. The only unload types are CSV, JSON and PARQUET, and JSON is written only as newline-delimited JSON. PARTITION BY splits the output into files by an expression. Unloads also have their own VALIDATION_MODE = RETURN_ROWS, which returns the rows the query would write so you can check them before any file is created.
Checkpoint 5 of 5· Check yourself
A downstream team will only accept one file shape from your nightly unload extract. Which of the shapes they suggested can Snowflake actually write?
Unloading supports only CSV, JSON and PARQUET, and JSON is written only as newline-delimited JSON. Avro and XML are load-only formats. A comma-separated JSON array can be loaded but is never produced by an unload.
“When you unload table data to files, Snowflake outputs only to NDJSON format.”Source: docs.snowflake.com
Practise it for real
Load a staged CSV file safely: check it first, load it with an error policy, then inspect what was rejected.
1.Run CREATE STAGE my_int_stage ENCRYPTION = (TYPE = 'SNOWFLAKE_SSE'); and upload a CSV file to @my_int_stage with PUT.
Why: A named stage can be granted to other roles, and server-side encryption keeps files readable when they are downloaded.
You should see: LIST @my_int_stage shows the uploaded file.
2.Run COPY INTO mytable FROM @my_int_stage FILE_FORMAT = (TYPE = CSV SKIP_HEADER = 1) VALIDATION_MODE = 'RETURN_ERRORS';
Why: VALIDATION_MODE parses the files and reports errors without loading any rows.
You should see: A result set with ERROR, FILE, LINE and COLUMN_NAME for each problem, or no rows if the file is clean. The table is still empty.
3.Run the same COPY without VALIDATION_MODE, adding ON_ERROR = CONTINUE.
Why: CONTINUE loads the good rows and reports at most one error per file.
You should see: ROWS_PARSED is larger than ROWS_LOADED by the number of rows with errors.
4.Run SELECT * FROM TABLE(VALIDATE(mytable, JOB_ID => '_last'));
Why: VALIDATE lists every error from the last load in the session, not just the first.
You should see: All rejected rows with their errors. With ON_ERROR = ABORT_STATEMENT it would have returned nothing.
5.Run the CONTINUE load a second time.
Why: Load metadata records which files have already been loaded into the table.
You should see: The file is skipped and no rows are added.
Stuck? Get a nudge
If the second run loads rows again, check whether FORCE = TRUE was left in the statement.
Sources
(7)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Loads data from files to an existing table.”
↩︎ Loading staged files into a table with COPY INTO“Snowflake treats the path value as a prefix and performs a prefix match against the file name in the external location.”
↩︎ Loading staged files into a table with COPY INTO“Continue to load the file if errors are found.”
↩︎ ON_ERROR, VALIDATION_MODE and VALIDATE()“SKIP_FILE is slower than either CONTINUE or ABORT_STATEMENT.”
↩︎ ON_ERROR, VALIDATION_MODE and VALIDATE()“Skip a file when the number of error rows found in the file is equal to or exceeds the specified number.”
↩︎ ON_ERROR, VALIDATION_MODE and VALIDATE()“The COPY statement returns an error message for a maximum of one error found per data file.”
↩︎ ON_ERROR, VALIDATION_MODE and VALIDATE()“SKIP_FILE Skip a file when an error is found.”
↩︎ Exam trap 1 - 2.
“There is no requirement for your data files to have the same number and ordering of columns as your target table.”
↩︎ Loading staged files into a table with COPY INTO“Bulk loading relies on user-provided virtual warehouses”
↩︎ Loading staged files into a table with COPY INTO - 3.
“In this case, to prevent accidental reload, the command skips the file by default.”
↩︎ Load metadata: why a file is not loaded twice“Alternatively, set the FORCE option to load all files, ignoring load metadata if it exists.”
↩︎ Load metadata: why a file is not loaded twice“The copy option references load metadata, if available, to avoid data duplication, but also attempts to load files with expired load metadata.”
↩︎ Exam trap 3“Note that this option reloads files, potentially duplicating data in a table.”
↩︎ Prediction - 4.
“The copy history metadata has expired.”
↩︎ Load metadata: why a file is not loaded twice“returns all the errors encountered during the load, rather than just the first error.”
↩︎ ON_ERROR, VALIDATION_MODE and VALIDATE()“SELECT statements are used to transform data during a COPY INTO <table> operation.”
↩︎ ON_ERROR, VALIDATION_MODE and VALIDATE()“The validation returns no results for COPY statements that specify ON_ERROR = ABORT_STATEMENT (default value).”
↩︎ Exam trap 2 - 5.
“Unloads data from a table (or query) into one or more files in one of the following locations:”
↩︎ Unloading table data to files with COPY INTO“The files can then be downloaded from the stage/location using the GET command.”
↩︎ Unloading table data to files with COPY INTO - 6.
“When you unload table data to files, Snowflake outputs only to NDJSON format.”
↩︎ Unloading table data to files with COPY INTO
Also cited
“Table stages don't support transforming data while loading it (using a query as the source for the COPY command).”
↩︎ Checkpoint