Snowflake SQL Tutorial 125 - The Same CSV File Read Twice, Giving Different Data

Snowflake SQL · Episode 125

In this post we are going to cover file format objects in Snowflake.

A file format is not a file. It is a named bundle of parsing settings, and you point a read or a load at it by name.

The whole post is one CSV file, read twice, giving different data both times. Same bytes on the stage, same query shape, different answers. We will start by making a format that names nothing at all and see what it turns out to contain.

Every query below was run on a real Snowflake account, and every result you see is the output it gave back.

Episode 125 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.

Let's put two files on a stage

We need a stage and two files: a deliberately messy CSV and some JSON.

Setup
-- A stage to put two files in.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

CREATE OR REPLACE STAGE STAGE_T125;

Both go up with the compression turned off, so the names stay as they are.

Query
PUT 'file://C:/your/folder/t125_messy.csv' @STAGE_T125/csv/ AUTO_COMPRESS = FALSE;
Result1 row · 8 columns · scroll →
Scroll sideways for the status column.
sourcetargetsource_sizetarget_sizesource_compressiontarget_compressionstatusmessage
t125_messy.csvt125_messy.csv123128NONENONEUPLOADED
Query
PUT 'file://C:/your/folder/t125_events.json' @STAGE_T125/json/ AUTO_COMPRESS = FALSE;
Result1 row · 8 columns · scroll →
Scroll sideways for the status column.
sourcetargetsource_sizetarget_sizesource_compressiontarget_compressionstatusmessage
t125_events.jsont125_events.json151160NONENONEUPLOADED

The local paths say C:/your/folder, which is what the shared demo script says too. Point them at a folder of your own.

Query
LIST @STAGE_T125/;
Result2 rows · 4 columns
namesizemd5last_modified
stage_t125/csv/t125_messy.csv128295bcab870e1a69689476ba4ea9934efWed, 30 Sep 2026 11:04:44 GMT
stage_t125/json/t125_events.json160ab72b7cf16de1da72a20c16a8064f4d2Wed, 30 Sep 2026 11:04:45 GMT

Two files, in two prefixes. We are going to look at the CSV one only through Snowflake's eyes, which is the point of the post.

Let's make a file format that names nothing

TYPE = CSV, and nothing else at all.

Query
CREATE OR REPLACE FILE FORMAT BARE_T125 TYPE = CSV;
Result1 row · 1 column
status
File format BARE_T125 successfully created.

Now let's ask Snowflake what we just made.

Query
DESCRIBE FILE FORMAT BARE_T125;
Result24 rows · 4 columns
The whole thing, as it came back.
propertyproperty_typeproperty_valueproperty_default
TYPEStringCSVCSV
RECORD_DELIMITERString\n\n
FIELD_DELIMITERString,,
FILE_EXTENSIONString
SKIP_HEADERInteger00
PARSE_HEADERBooleanfalsefalse
DATE_FORMATStringAUTOAUTO
TIME_FORMATStringAUTOAUTO
TIMESTAMP_FORMATStringAUTOAUTO
BINARY_FORMATStringHEXHEX
ESCAPEStringNONENONE
ESCAPE_UNENCLOSED_FIELDString\\\\
TRIM_SPACEBooleanfalsefalse
FIELD_OPTIONALLY_ENCLOSED_BYStringNONENONE
NULL_IFList[\\N][\\N]
COMPRESSIONStringAUTOAUTO
ERROR_ON_COLUMN_COUNT_MISMATCHBooleantruetrue
VALIDATE_UTF8Booleantruetrue
SKIP_BLANK_LINESBooleanfalsefalse
REPLACE_INVALID_CHARACTERSBooleanfalsefalse
EMPTY_FIELD_AS_NULLBooleantruetrue
SKIP_BYTE_ORDER_MARKBooleantruetrue
ENCODINGStringUTF8UTF8
MULTI_LINEBooleantruetrue

Twenty-four rows, for a statement with one setting in it.

Two of those columns are the story. Read property_value and property_default side by side, all the way down. They are identical on every single row.

So naming nothing did not give us a neutral reader. It gave us twenty-four decisions, made for us.

Where you have seen this before

Two posts ago, DESCRIBE STAGE returned thirty-four rows for a stage we created with a name and a comment. Now you know why. Most of those rows were a file format, exactly like this one, with the stage's own copy options and directory settings on top.

Now let's pull out the handful that will actually bite us.

Query
SELECT "property" AS THE_SETTING, "property_value" AS THE_VALUE,
       "property_default" AS THE_DEFAULT
FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
WHERE "property" IN ('SKIP_HEADER', 'FIELD_OPTIONALLY_ENCLOSED_BY',
                     'NULL_IF', 'TRIM_SPACE', 'EMPTY_FIELD_AS_NULL')
ORDER BY "property";
Result5 rows · 3 columns
THE_SETTINGTHE_VALUETHE_DEFAULT
EMPTY_FIELD_AS_NULLtruetrue
FIELD_OPTIONALLY_ENCLOSED_BYNONENONE
NULL_IF[\\N][\\N]
SKIP_HEADER00
TRIM_SPACEfalsefalse

Five settings, and every one of them is worth reading out loud.

  • SKIP_HEADER is 0, so a header row is data.
  • FIELD_OPTIONALLY_ENCLOSED_BY is NONE, so a double quote is just a character.
  • NULL_IF is [\\N]. Not the word NULL, and not an empty field.
  • TRIM_SPACE is false, so padding stays on.
  • EMPTY_FIELD_AS_NULL is true. Remember that last one, because it is the one that catches people out.

Now let's read the messy file through it

Four positions, $1 to $4, through the format that names nothing.

Query
SELECT $1 AS COLUMN_1, $2 AS COLUMN_2, $3 AS COLUMN_3, $4 AS COLUMN_4
FROM @STAGE_T125/csv/ (FILE_FORMAT => 'BARE_T125');
Result5 rows · 4 columns
COLUMN_1COLUMN_2COLUMN_3COLUMN_4
idregionnoteamount
1north"hello world"
2southNULL200.00
3eastNULL300.00
4 west "say ""hi"""400.00

Five rows, and three things have gone wrong in them.

The first row is id, region, note, amount. That is the header, being handed to us as data, because SKIP_HEADER is zero.

Then look at the row with 1 in the first column. COLUMN_3 is "hello and COLUMN_4 is world". The file has one quoted field with a comma inside it, and because FIELD_OPTIONALLY_ENCLOSED_BY is NONE the comma split it in two and shifted everything after it one place to the right.

And the last row. The region has spaces on both sides of it, because TRIM_SPACE is false, and the note is the raw text with its doubled quotes still in it.

Now let's count all of that rather than look at it.

Query
SELECT COUNT(*)                               AS ROWS_IT_FOUND,
       SUM(IFF($1 = 'id', 1, 0))              AS ROWS_THAT_ARE_THE_HEADER,
       SUM(IFF($3 IS NULL, 1, 0))             AS ROWS_WITH_A_NULL_NOTE,
       SUM(IFF($2 = 'west', 1, 0))            AS ROWS_WHERE_REGION_IS_EXACTLY_WEST
FROM @STAGE_T125/csv/ (FILE_FORMAT => 'BARE_T125');
Result1 row · 4 columns
ROWS_IT_FOUNDROWS_THAT_ARE_THE_HEADERROWS_WITH_A_NULL_NOTEROWS_WHERE_REGION_IS_EXACTLY_WEST
5110

Five rows found. One of them is the header. Zero rows where the region is exactly west, because of the padding. And one row with a null note.

Two cells print NULL and only one of them is one

Go back to that grid and look at the two middle rows. The note column reads NULL on both of them, and they look identical.

The count beside it says only one row has a null note.

Here is what is in the file. One of those two notes is the literal word NULL, four characters of text. The other is an empty field. EMPTY_FIELD_AS_NULL is true, so the empty one became a real null, and NULL_IF does not list the word, so the word stayed a string.

Which row is which? I did not capture a query that answers that, so I am not going to tell you. What I will tell you is that your eyes cannot do this and the count can.

The habit to take from this post

A grid showing you NULL is a grid telling you two different things with the same four letters. If that distinction matters in your data, test it with COUNT, SUM(IFF(col IS NULL, 1, 0)) or col = 'NULL', and never with a screenshot.

Now let's name the four settings and read it again

Same file, same bytes on the stage. The only thing that changes is the format we read it through.

Query
CREATE OR REPLACE FILE FORMAT SPELLED_T125
    TYPE = CSV
    SKIP_HEADER = 1
    FIELD_OPTIONALLY_ENCLOSED_BY = '"'
    NULL_IF = ('NULL', '\\N', '')
    TRIM_SPACE = TRUE;
Result1 row · 1 column
status
File format SPELLED_T125 successfully created.

Skip the header, let a double quote enclose a field, trim the padding, and treat the word NULL, the escape sequence and the empty string all as nulls.

Query
SELECT $1 AS ID, $2 AS REGION, $3 AS NOTE, $4 AS AMOUNT
FROM @STAGE_T125/csv/ (FILE_FORMAT => 'SPELLED_T125')
ORDER BY $1;
Result4 rows · 4 columns
IDREGIONNOTEAMOUNT
1northhello, world100.00
2southNULL200.00
3eastNULL300.00
4westsay "hi"400.00

Four rows this time. The header is gone. hello, world is one value in one column, where it belongs. say "hi" has its real quotes. And west has no padding on it.

And the same four counts.

Query
SELECT COUNT(*)                               AS ROWS_IT_FOUND,
       SUM(IFF($1 = 'id', 1, 0))              AS ROWS_THAT_ARE_THE_HEADER,
       SUM(IFF($3 IS NULL, 1, 0))             AS ROWS_WITH_A_NULL_NOTE,
       SUM(IFF($2 = 'west', 1, 0))            AS ROWS_WHERE_REGION_IS_EXACTLY_WEST
FROM @STAGE_T125/csv/ (FILE_FORMAT => 'SPELLED_T125');
Result1 row · 4 columns
ROWS_IT_FOUNDROWS_THAT_ARE_THE_HEADERROWS_WITH_A_NULL_NOTEROWS_WHERE_REGION_IS_EXACTLY_WEST
4021

Four rows found, none of them a header, one row where the region is exactly west, and two null notes instead of one. Both of them are real nulls now, because we put the word in NULL_IF.

Let's put the one row that caused the most trouble side by side, read both ways at once.

Query
SELECT 'names nothing' AS WHICH_FORMAT, $1 AS COLUMN_1, $2 AS COLUMN_2, $3 AS COLUMN_3
FROM @STAGE_T125/csv/ (FILE_FORMAT => 'BARE_T125') WHERE $1 = '1'
UNION ALL
SELECT 'names the four', $1, $2, $3
FROM @STAGE_T125/csv/ (FILE_FORMAT => 'SPELLED_T125') WHERE $1 = '1';
Result2 rows · 4 columns
WHICH_FORMATCOLUMN_1COLUMN_2COLUMN_3
names nothing1north"hello
names the four1northhello, world

Two rows, one query, one file. That is the whole point of a file format object. Same bytes on the stage, different data in your result.

And the brackets take more than a format name

The brackets on a stage read are not only for the format. PATTERN goes in there too, as we saw in the last post.

Query
SELECT $1 AS ID, $2 AS REGION, $3 AS NOTE
FROM @STAGE_T125/csv/ (FILE_FORMAT => 'BARE_T125', PATTERN => '.*messy.*')
LIMIT 2;
Result2 rows · 3 columns
IDREGIONNOTE
idregionnote
1north"hello

Two rows, and they are the first two of the five we got earlier, with three positions asked for instead of four: the header, and the row with the split quote. Nothing about the format changed here. PATTERN chooses which files the read opens, and it is not one of the twenty-four properties a format carries.

Worth being clear about, because the two sit in the same brackets and look like the same kind of thing. The format says how to parse. The pattern says what to open.

Where do those settings actually live?

SHOW FILE FORMATS lists them.

Query
SHOW FILE FORMATS LIKE '%\\_T125' IN SCHEMA PUBLIC;
Result2 rows · 9 columns · scroll →
Nine columns, and one of them is very wide. Scroll sideways for it.
created_onnamedatabase_nameschema_nametypeownercommentformat_optionsowner_role_type
2026-09-30 04:04:44.264000-07:00BARE_T125DEMO_DBPUBLICCSVACCOUNTADMIN{"TYPE":"CSV","RECORD_DELIMITER":"\n","FIELD_DELIMITER":",","FILE_EXTENSION":null,"SKIP_HEADER":0,"PARSE_HEADER":false,"DATE_FORMAT":"AUTO","TIME_FORMAT":"AUTO","TIMESTAMP_FORMAT":"AUTO","BINARY_FORMAT":"HEX","ESCAPE":"NONE","ESCAPE_UNENCLOSED_FIELD":"\\","TRIM_SPACE":false,"FIELD_OPTIONALLY_ENCLOSED_BY":"NONE","NULL_IF":["\\N"],"COMPRESSION":"AUTO","ERROR_ON_COLUMN_COUNT_MISMATCH":true,"VALIDATE_UTF8":true,"SKIP_BLANK_LINES":false,"REPLACE_INVALID_CHARACTERS":false,"EMPTY_FIELD_AS_NULL":true,"SKIP_BYTE_ORDER_MARK":true,"ENCODING":"UTF8","MULTI_LINE":true}ROLE
2026-09-30 04:04:45.590000-07:00SPELLED_T125DEMO_DBPUBLICCSVACCOUNTADMIN{"TYPE":"CSV","RECORD_DELIMITER":"\n","FIELD_DELIMITER":",","FILE_EXTENSION":null,"SKIP_HEADER":1,"PARSE_HEADER":false,"DATE_FORMAT":"AUTO","TIME_FORMAT":"AUTO","TIMESTAMP_FORMAT":"AUTO","BINARY_FORMAT":"HEX","ESCAPE":"NONE","ESCAPE_UNENCLOSED_FIELD":"\\","TRIM_SPACE":true,"FIELD_OPTIONALLY_ENCLOSED_BY":"\"","NULL_IF":["NULL","\\N",""],"COMPRESSION":"AUTO","ERROR_ON_COLUMN_COUNT_MISMATCH":true,"VALIDATE_UTF8":true,"SKIP_BLANK_LINES":false,"REPLACE_INVALID_CHARACTERS":false,"EMPTY_FIELD_AS_NULL":true,"SKIP_BYTE_ORDER_MARK":true,"ENCODING":"UTF8","MULTI_LINE":true}ROLE

Nine columns, and the one worth stopping on is format_options. That single cell is the entire settings set as one JSON blob, every one of the twenty-four, spelled out, for both of our formats.

Read the two blobs against each other and you can see exactly what we changed: SKIP_HEADER, TRIM_SPACE, FIELD_OPTIONALLY_ENCLOSED_BY and NULL_IF, and nothing else.

Empty, null, and the word null

There is a small thing in those two grids that is worth knowing about. DESCRIBE FILE FORMAT reports FILE_EXTENSION as an empty string, which shows up as an empty cell marked empty. The format_options blob writes the same setting as the four characters null inside its JSON. Same format, same setting, two ways of saying it has no value, and neither of them is a real SQL NULL.

A SHOW is a command rather than a query, so let's read its output back as a grid.

Query
SELECT "name" AS THE_NAME, "type" AS THE_TYPE, "comment" AS THE_COMMENT
FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
ORDER BY "name";
Result2 rows · 3 columns
THE_NAMETHE_TYPETHE_COMMENT
BARE_T125CSV
SPELLED_T125CSV

Two formats, both CSV, both with an empty comment because we never gave them one.

And there is a catalog view as well, which is easier to query than a SHOW.

Query
SELECT FILE_FORMAT_NAME, FILE_FORMAT_TYPE, FIELD_DELIMITER, SKIP_HEADER,
       FIELD_OPTIONALLY_ENCLOSED_BY, NULL_IF
FROM INFORMATION_SCHEMA.FILE_FORMATS
WHERE RIGHT(FILE_FORMAT_NAME, 5) = '_T125'
ORDER BY FILE_FORMAT_NAME;
Result2 rows · 6 columns · scroll →
FILE_FORMAT_NAMEFILE_FORMAT_TYPEFIELD_DELIMITERSKIP_HEADERFIELD_OPTIONALLY_ENCLOSED_BYNULL_IF
BARE_T125CSV,0NONE["\\N"]
SPELLED_T125CSV,1"["NULL","\\N",""]

One line each, with the settings we care about as real columns. The bare one has a SKIP_HEADER of 0 and NONE for its enclosing character. The spelled-out one has 1, a double quote, and a list of three things to treat as null.

Six types, and one that is not a type

CSV is one of six. Let's make the other five, each with nothing but a type.

JSON
CREATE OR REPLACE FILE FORMAT JSON_T125 TYPE = JSON;
Result1 row · 1 column
status
File format JSON_T125 successfully created.
PARQUET
CREATE OR REPLACE FILE FORMAT PARQUET_T125 TYPE = PARQUET;
Result1 row · 1 column
status
File format PARQUET_T125 successfully created.
AVRO
CREATE OR REPLACE FILE FORMAT AVRO_T125 TYPE = AVRO;
Result1 row · 1 column
status
File format AVRO_T125 successfully created.
ORC
CREATE OR REPLACE FILE FORMAT ORC_T125 TYPE = ORC;
Result1 row · 1 column
status
File format ORC_T125 successfully created.
XML
CREATE OR REPLACE FILE FORMAT XML_T125 TYPE = XML;
Result1 row · 1 column
status
File format XML_T125 successfully created.

All five created without a word of complaint. Now one that is not on the list.

Refused
CREATE OR REPLACE FILE FORMAT NONSENSE_T125 TYPE = YAML;
Query failed — Snowflake returned an error
001008 (22023): SQL compilation error:
invalid value [YAML] for parameter 'TYPE'

invalid value [YAML] for parameter 'TYPE'. So the list of types is closed, and Snowflake will tell you when you are off it.

And what about an option that belongs to a different type? FIELD_DELIMITER is a CSV setting. Let's put it on a JSON format.

Refused
CREATE OR REPLACE FILE FORMAT MIXED_T125
    TYPE = JSON
    FIELD_DELIMITER = ',';
Query failed — Snowflake returned an error
002135 (42601): SQL compilation error:
Option FIELD_DELIMITER is not valid for file format type JSON.

Option FIELD_DELIMITER is not valid for file format type JSON. It checks the option against the type and names the one it does not want. It does not quietly ignore it, which is the behaviour you would have to go looking for otherwise.

Now let's read the JSON file, twice

First with the JSON format, which is the right one.

Query
SELECT $1 AS THE_WHOLE_OBJECT
FROM @STAGE_T125/json/ (FILE_FORMAT => 'JSON_T125');
Result3 rows · 1 column
THE_WHOLE_OBJECT
{ "amount": 10.5, "event_id": 1, "kind": "click" }
{ "amount": 0, "event_id": 2, "kind": "view" }
{ "amount": 7.25, "event_id": 3, "kind": "click" }

Three rows for three objects, and $1 is the whole object each time rather than a field of it.

So we pick the fields out with a colon.

Query
SELECT $1:event_id::INT     AS EVENT_ID,
       $1:kind::VARCHAR     AS KIND,
       $1:amount::NUMBER(10,2) AS AMOUNT
FROM @STAGE_T125/json/ (FILE_FORMAT => 'JSON_T125')
ORDER BY EVENT_ID;
Result3 rows · 3 columns
EVENT_IDKINDAMOUNT
1click10.50
2view0.00
3click7.25

Three events, with their kind and their amount, cast into real types.

Now the one that should worry you. The same JSON file, read through the bare CSV format.

Query
SELECT $1 AS COLUMN_1, $2 AS COLUMN_2
FROM @STAGE_T125/json/ (FILE_FORMAT => 'BARE_T125');
Result3 rows · 2 columns
COLUMN_1COLUMN_2
{"event_id": 1 "kind": "click"
{"event_id": 2 "kind": "view"
{"event_id": 3 "kind": "click"

It did not refuse. It split the JSON on the comma, because splitting on a comma is exactly what we told it to do.

The quiet one

Naming the wrong format is not an error. It is wrong data, delivered quietly, in the right number of rows. Nothing in that grid is flagged, nothing is missing, and every value in it is useless. This is the failure mode to watch for in a pipeline, because it does not raise anything for you to catch.

Which of these can COPY INTO unload with?

A file format is used for writing as well as reading. Let's make a small table and try each type in turn.

Query
CREATE OR REPLACE TABLE SALES_T125 (
    SALE_ID INT, REGION VARCHAR(10), AMOUNT NUMBER(10,2)
);
Result1 row · 1 column
status
Table SALES_T125 successfully created.
Query
INSERT INTO SALES_T125 (SALE_ID, REGION, AMOUNT)
VALUES (1, 'north', 100.00), (2, 'south', 250.50),
       (3, 'east',   75.25), (4, 'west',  310.00);
Result1 row · 1 column
number of rows inserted
4

Now CSV, with the spelled-out format.

Query
COPY INTO @STAGE_T125/out_csv/ FROM SALES_T125
FILE_FORMAT = (FORMAT_NAME = 'SPELLED_T125') OVERWRITE = TRUE;
Result1 row · 3 columns
rows_unloadedinput_bytesoutput_bytes
46577

Four rows unloaded. Then JSON, which needs an OBJECT_CONSTRUCT because a JSON file holds objects rather than rows of columns.

Query
COPY INTO @STAGE_T125/out_json/ FROM
    (SELECT OBJECT_CONSTRUCT('sale_id', SALE_ID, 'region', REGION,
                             'amount', AMOUNT) FROM SALES_T125)
FILE_FORMAT = (FORMAT_NAME = 'JSON_T125') OVERWRITE = TRUE;
Result1 row · 3 columns
rows_unloadedinput_bytesoutput_bytes
4178107

And Parquet, straight from the table.

Query
COPY INTO @STAGE_T125/out_parquet/ FROM SALES_T125
FILE_FORMAT = (FORMAT_NAME = 'PARQUET_T125') OVERWRITE = TRUE;
Result1 row · 3 columns
rows_unloadedinput_bytesoutput_bytes
4879879

Four rows each time. Now the other three.

Refused
COPY INTO @STAGE_T125/out_avro/ FROM SALES_T125
FILE_FORMAT = (FORMAT_NAME = 'AVRO_T125') OVERWRITE = TRUE;
Query failed — Snowflake returned an error
002330 (22023): SQL compilation error: Unload not yet implemented for file format 'AVRO'
Refused
COPY INTO @STAGE_T125/out_orc/ FROM SALES_T125
FILE_FORMAT = (FORMAT_NAME = 'ORC_T125') OVERWRITE = TRUE;
Query failed — Snowflake returned an error
002330 (22023): SQL compilation error: Unload not yet implemented for file format 'ORC'
Refused
COPY INTO @STAGE_T125/out_xml/ FROM SALES_T125
FILE_FORMAT = (FORMAT_NAME = 'XML_T125') OVERWRITE = TRUE;
Query failed — Snowflake returned an error
002330 (22023): SQL compilation error: Unload not yet implemented for file format 'XML'

Unload not yet implemented for file format, three times, each one naming its own type.

So you can create a file format that COPY INTO will not write with. The CREATE succeeding told us nothing about that.

Let's see what actually got written.

Query
LIST @STAGE_T125/;
Result5 rows · 4 columns
namesizemd5last_modified
stage_t125/csv/t125_messy.csv128295bcab870e1a69689476ba4ea9934efWed, 30 Sep 2026 11:04:44 GMT
stage_t125/json/t125_events.json160ab72b7cf16de1da72a20c16a8064f4d2Wed, 30 Sep 2026 11:04:45 GMT
stage_t125/out_csv/data_0_0_0.csv.gz8066c0d2a6789d3ec7f808047fd0f78ec0Wed, 30 Sep 2026 11:04:51 GMT
stage_t125/out_json/data_0_0_0.json.gz112db75868cd1aa4f87994eb5049268ed70Wed, 30 Sep 2026 11:04:51 GMT
stage_t125/out_parquet/data_0_0_0.snappy.parquet880720dd3a94249bfb03c34492facc571fbWed, 30 Sep 2026 11:04:52 GMT
Query
SELECT "name" AS THE_FILE, "size" AS SIZE_IN_BYTES
FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
ORDER BY "name";
Result5 rows · 2 columns
THE_FILESIZE_IN_BYTES
stage_t125/csv/t125_messy.csv128
stage_t125/json/t125_events.json160
stage_t125/out_csv/data_0_0_0.csv.gz80
stage_t125/out_json/data_0_0_0.json.gz112
stage_t125/out_parquet/data_0_0_0.snappy.parquet880

Five files. The two we uploaded, plus one each from the three unloads that worked. And look at the names Snowflake chose: data_0_0_0.csv.gz, data_0_0_0.json.gz and data_0_0_0.snappy.parquet. Compressed again, without being asked.

One last thing I got wrong: reading the Parquet back

We have a Parquet file that came out of a table with three named columns in it. So let's read it back by those names.

Query
SELECT $1:SALE_ID::INT          AS SALE_ID,
       $1:REGION::VARCHAR       AS REGION,
       $1:AMOUNT::NUMBER(10,2)  AS AMOUNT
FROM @STAGE_T125/out_parquet/ (FILE_FORMAT => 'PARQUET_T125')
ORDER BY SALE_ID;
Result4 rows · 3 columns
SALE_IDREGIONAMOUNT
NULLNULLNULL
NULLNULLNULL
NULLNULLNULL
NULLNULLNULL

Four rows, and every single value is a null.

So I checked whether the data was in the file at all.

Query
SELECT (SELECT COUNT(*) FROM SALES_T125) AS ROWS_IN_THE_TABLE,
       (SELECT SUM(AMOUNT) FROM SALES_T125) AS TOTAL_IN_THE_TABLE,
       (SELECT COUNT(*) FROM @STAGE_T125/out_parquet/
            (FILE_FORMAT => 'PARQUET_T125')) AS ROWS_IN_THE_PARQUET;
Result1 row · 3 columns
ROWS_IN_THE_TABLETOTAL_IN_THE_TABLEROWS_IN_THE_PARQUET
4735.754

Four rows in the table and four rows in the Parquet file. The rows are there. The names are not.

COPY INTO straight from a table did not carry my column names into the file in the form I asked for them back. I did not capture a query that says what it called them instead, so I am not going to guess at it here.

The fix is further up this page. The JSON unload went through a SELECT with OBJECT_CONSTRUCT, where you name every field yourself. Name them on the way out and they are yours on the way back in.

And let's tidy up

Five files, one stage, seven formats and a table. The two formats that were refused get a drop as well, because a script should clean up after the statements that failed too.

Cleanup
-- Put the schema back the way we found it.
REMOVE @STAGE_T125/;
DROP STAGE IF EXISTS STAGE_T125;

DROP FILE FORMAT IF EXISTS BARE_T125;
DROP FILE FORMAT IF EXISTS SPELLED_T125;
DROP FILE FORMAT IF EXISTS JSON_T125;
DROP FILE FORMAT IF EXISTS PARQUET_T125;
DROP FILE FORMAT IF EXISTS AVRO_T125;
DROP FILE FORMAT IF EXISTS ORC_T125;
DROP FILE FORMAT IF EXISTS XML_T125;

-- These two were refused on purpose and never existed. A probe script should
-- clean up after the statements that failed as well as the ones that worked.
DROP FILE FORMAT IF EXISTS MIXED_T125;
DROP FILE FORMAT IF EXISTS NONSENSE_T125;

DROP TABLE IF EXISTS SALES_T125;
Query
REMOVE @STAGE_T125/;
Result5 rows · 2 columns
nameresult
stage_t125/out_csv/data_0_0_0.csv.gzremoved
stage_t125/json/t125_events.jsonremoved
stage_t125/out_json/data_0_0_0.json.gzremoved
stage_t125/csv/t125_messy.csvremoved
stage_t125/out_parquet/data_0_0_0.snappy.parquetremoved
Query
LIST @STAGE_T125/;
Result0 rows · 4 columns
namesizemd5last_modified

Then the formats, including the two that never existed.

Query
DROP FILE FORMAT IF EXISTS MIXED_T125;
Result1 row · 1 column
status
Drop statement executed successfully (MIXED_T125 already dropped).
Query
DROP FILE FORMAT IF EXISTS NONSENSE_T125;
Result1 row · 1 column
status
Drop statement executed successfully (NONSENSE_T125 already dropped).

already dropped on both of those, which is what IF EXISTS says about something that was never there.

Query
SELECT CURRENT_DATABASE()                 AS THE_DATABASE,
       CURRENT_SCHEMA()                   AS THE_SCHEMA,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
        WHERE RIGHT(TABLE_NAME, 5) = '_T125') AS PROBE_TABLES_LEFT,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STAGES
        WHERE RIGHT(STAGE_NAME, 5) = '_T125') AS PROBE_STAGES_LEFT,
       (SELECT COUNT(*) FROM INFORMATION_SCHEMA.FILE_FORMATS
        WHERE RIGHT(FILE_FORMAT_NAME, 5) = '_T125') AS PROBE_FORMATS_LEFT,
       (SELECT COUNT(*) FROM CUSTOMERS)   AS DEMO_DB_IS_READABLE;
Result1 row · 6 columns · scroll →
THE_DATABASETHE_SCHEMAPROBE_TABLES_LEFTPROBE_STAGES_LEFTPROBE_FORMATS_LEFTDEMO_DB_IS_READABLE
DEMO_DBPUBLIC00010

No probe tables, no probe stages, no probe file formats, and the demo database still reads. Back where we started.

Key points

  • A file format is a named bundle of parsing settings, and DESCRIBE FILE FORMAT on a CSV one returns twenty-four rows.
  • On a format that names nothing, every value equals its own default. So it is not a neutral reader. It is a full set of decisions made for you.
  • The defaults that bite a CSV read are SKIP_HEADER 0, FIELD_OPTIONALLY_ENCLOSED_BY NONE, NULL_IF [\\N], TRIM_SPACE false and EMPTY_FIELD_AS_NULL true.
  • Through the bare format the messy file gives five rows. Through the spelled-out one it gives four. Same bytes on the stage.
  • A quoted comma splits a field in two when FIELD_OPTIONALLY_ENCLOSED_BY is NONE, and everything after it shifts right.
  • Two cells can both print NULL while only one of them is a null. Check that with a count, not with your eyes.
  • PATTERN sits in the same brackets as the format but is not one of the format's properties. The format says how to parse, the pattern says what to open.
  • SHOW FILE FORMATS carries the whole settings set in one format_options cell, and INFORMATION_SCHEMA.FILE_FORMATS puts the useful ones in columns.
  • All six types create with nothing but a name. TYPE = YAML does not, and says so.
  • A CSV option on a JSON format is refused by name rather than ignored.
  • Reading JSON through a CSV format is not refused. It splits the JSON on the comma and hands you the result.
  • CSV, JSON and Parquet unload. AVRO, ORC and XML are refused with Unload not yet implemented, so a format that creates is not necessarily a format you can write with.
  • An unload arrives compressed without being asked: .csv.gz, .json.gz, .snappy.parquet.
  • Reading an unloaded Parquet file back by the table's column names gave four rows of nulls with the right row count. Name the fields yourself with OBJECT_CONSTRUCT on the way out.
Next in this series

Episode 126 — COPY INTO, properly. With stages, PUT and file formats behind us, the load itself — and the thing it remembers about your files that makes the second run of the same statement do nothing at all.

Every query and every result grid on this page was captured from a live Snowflake account (version 10.35.101) running the demo script for this episode. The local folder in the PUT statements is written as C:/your/folder, the same substitution the shared demo script makes; nothing else in any statement is changed and no error message is edited. The contents of the messy CSV file are not printed anywhere on this page, because the only honest look at it is the one Snowflake gives us through a format, and because the episode deliberately does not say which of its two blank-looking notes is a real null. Cells marked empty are empty strings, cells reading NULL in grey are real nulls, and the four characters null inside the format_options blob are part of a JSON text value: three different things that this page shows all three of. Nothing on this page is timed; the byte counts are Snowflake's own report columns, quoted as they came back, and no performance claims are made anywhere in this series. File format behaviour follows the Snowflake CREATE FILE FORMAT documentation.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.