Sub topic 4
File formats and FORMAT_OPTIONS
This chapter assumes you can write a basic COPY INTO statement, as shown in the previous chapter. You also need to know what a Delta table is. You should be able to recognize CSV, JSON, and Parquet files by their structure. Here you will learn how FILEFORMAT tells COPY INTO how to read files, and how FORMAT_OPTIONS adjusts the parsing.
Two clauses, two jobs
Every COPY INTO statement needs a FILEFORMAT clause. It names the reader that turns bytes in the source files into rows. FORMAT_OPTIONS is optional. It passes settings to that reader.
FILEFORMAT accepts these values:
| Value | Typical source | Notes |
|---|---|---|
| `CSV` | Exports from databases and spreadsheets | Most options, most surprises |
| `JSON` | API dumps, event logs | Line-delimited by default |
| `PARQUET` | Output from other Spark jobs | Carries its own schema |
| `AVRO` | Kafka exports | Carries its own schema |
| `ORC` | Hive-era data | Carries its own schema |
| `TEXT` | Raw log lines | One row per line, one `value` column |
| `BINARYFILE` | Images, PDFs | One row per file, with path and content |
| `DELTA` | Another Delta table's files | Loads from a Delta location |
Self-describing formats (Parquet, Avro, ORC) need few options. Text formats (CSV, JSON) leave the reader guessing, so they need most of your attention.
Option syntax
FORMAT_OPTIONS takes a list of key-value pairs. Both the key and the value are string literals, even for booleans and numbers.
COPY INTO main.sales.orders
FROM '/Volumes/main/sales/landing/orders/'
FILEFORMAT = CSV
FORMAT_OPTIONS (
'header' = 'true',
'delimiter' = '|',
'nullValue' = 'NA'
);Writing 'header' = true without quotes is a syntax error. Option names are case-insensitive in most readers, but use the documented spelling so your code is easy to search.
CSV options you will use most
CSV has no schema, no types, and no single standard. These options cover most of the variation you will meet.
| Option | Default | What it does | Column |
|---|---|---|---|
| `header` | `false` | Treats the first line of each file as column names | |
| `delimiter` | `,` | Sets the field separator, such as `\ | `, `;`, or `\t` |
| `quote` | `"` | Sets the character that wraps fields containing delimiters | |
| `escape` | `\` | Sets the character that escapes a quote inside a quoted field | |
| `multiLine` | `false` | Allows quoted fields to span several lines | |
| `nullValue` | empty string | Sets the text that should become SQL `NULL` | |
| `dateFormat` | `yyyy-MM-dd` | Sets the pattern for parsing date columns | |
| `timestampFormat` | a standard ISO-style pattern | Sets the pattern for parsing timestamp columns | |
| `encoding` | `UTF-8` | Sets the character set of the files | |
| `inferSchema` | `false` | Samples the data to guess column types | |
| `mode` | `PERMISSIVE` | Sets how to handle rows that fail to parse |
Headers
With 'header' = 'true', each file's first row is read as column names. Without it, columns are named _c0, _c1, and so on. If you load into a table that already has columns, header names must be usable for matching. Leave the header off for headerless files, and then list the columns in a SELECT source (covered in a later chapter) to give them names.
Delimiters and quoting
A file with semicolons, common in European locales, needs 'delimiter' = ';'. Tab-separated files use 'delimiter' = '\t'. A field such as "Smith, Jane" survives a comma delimiter because of the quote character. If a quoted field contains an embedded line break, add 'multiLine' = 'true'. Without it, one record is split across two rows and both fail to parse.
COPY INTO main.sales.customers
FROM '/Volumes/main/sales/landing/customers/'
FILEFORMAT = CSV
FORMAT_OPTIONS (
'header' = 'true',
'delimiter' = ';',
'multiLine' = 'true',
'quote' = '"',
'escape' = '"',
'encoding' = 'ISO-8859-1'
);Setting escape to " matches files that write an embedded quote by doubling it (""). This is the convention most spreadsheet exports use.
Nulls and dates
CSV has no null type. An empty field is read as NULL by default, but many systems write NA, \N, or NULL as literal text. If you do not map that text, it ends up as a string in your data. When the target column is numeric, a literal NA can make the cast fail or produce NULL, depending on the mode. Set nullValue to the exact text your source uses. Dates work the same way: if the files hold 04/12/2026, set 'dateFormat' = 'dd/MM/yyyy'. Use Spark datetime patterns, where MM is month and mm is minute.
Type inference
With 'inferSchema' = 'true', the reader samples the data and picks types. Without it, every CSV column is read as a string. Inference costs an extra pass over the data and can guess wrong. A column that holds 001, 002 becomes an integer and loses its leading zeros. For tables that already exist, skip inference and let the target schema drive the types. The target-schema chapter covers this in depth.
JSON options
By default, the JSON reader expects one complete JSON object per line, often called JSON Lines. A file holding one large array or a pretty-printed object spanning many lines needs 'multiLine' = 'true'.
COPY INTO main.sales.events_raw
FROM '/Volumes/main/sales/landing/events/'
FILEFORMAT = JSON
FORMAT_OPTIONS (
'multiLine' = 'true',
'allowComments' = 'true',
'timestampFormat' = 'yyyy-MM-dd''T''HH:mm:ss'
);Note the doubled single quotes around the literal T. Inside a SQL string, '' is one single quote, and the date pattern then sees 'T', which marks T as literal text.
Other useful JSON options:
primitivesAsStringreads numbers and booleans as strings. This avoids type conflicts when one field is sometimes a number and sometimes text.allowSingleQuotesaccepts'key'as well as"key".dropFieldIfAllNullomits fields that are null in every sampled record when inferring the schema.
Some JSON reader options can also rescue data that does not match the expected schema into a separate column. Look for the rescued data column in the reader documentation for your runtime if your sources are messy.
Parquet, Avro, and ORC
These formats store column names and types inside each file, so a minimal statement often works.
COPY INTO main.sales.orders_parquet
FROM '/Volumes/main/sales/landing/orders_parquet/'
FILEFORMAT = PARQUET
FORMAT_OPTIONS ('mergeSchema' = 'true');Here mergeSchema inside FORMAT_OPTIONS tells the reader to combine the schemas of all files it reads in this run. This matters if files from different days have different columns. It is separate from the mergeSchema entry in COPY_OPTIONS, which lets the target table gain new columns. You may need both. Schema evolution gets its own chapter, so for now just keep the two placements distinct.
Options that apply to many formats
Some options work with several file formats because they control file discovery and error handling, not parsing.
| Option | Effect |
|---|---|
| `ignoreCorruptFiles` | Skips files that cannot be read instead of failing the whole statement |
| `ignoreMissingFiles` | Skips files that disappear between listing and reading |
| `modifiedAfter`, `modifiedBefore` | Loads only files modified in a time window, given as timestamp strings |
| `pathGlobFilter` | Filters by file name pattern |
| `recursiveFileLookup` | Reads files in nested subfolders |
These overlap with the PATTERN and FILES clauses from the file-selection chapter. Use PATTERN for name-based selection. Reach for modifiedAfter when selection depends on arrival time.
Handling bad rows
The CSV mode option decides what happens to a row that does not fit the schema:
PERMISSIVEkeeps the row and sets fields it cannot parse toNULL. This is the default.DROPMALFORMEDsilently discards bad rows.FAILFASTstops the load on the first bad row.
For a production load, FAILFAST is the safest choice if you want to learn about bad data immediately. PERMISSIVE fits loads where partial data is acceptable and you check null rates afterward. Be careful with DROPMALFORMED, because the lost rows leave no trace.
Common errors
- A misspelled option name. Readers often ignore options they do not recognize, so a typo such as
'hedaer' = 'true'may not raise an error. The symptom is that the first data row is loaded as data. Compare your option spelling with the documentation when output looks wrong. - The wrong
FILEFORMATfor the files. Reading JSON Lines as CSV gives one wide string column or a parse error. Open one file and confirm its structure first. - Booleans without quotes.
'header' = truefails to parse. All values are strings. - Expecting
inferSchemato type everything. Inference only helps when the target table does not already define the columns. - Mixed layouts in one folder. If one file has a header and another does not, a single
headersetting cannot read both correctly. Separate them withPATTERN.
Exercise
A vendor sends semicolon-delimited CSV files with a header row. Missing values are written as the text NA, and dates look like 31/12/2026. Write the FORMAT_OPTIONS clause that reads these files correctly.
Show answer
FORMAT_OPTIONS ('header' = 'true', 'delimiter' = ';', 'nullValue' = 'NA', 'dateFormat' = 'dd/MM/yyyy'). All keys and values are quoted strings. The delimiter handles the semicolons, nullValue turns the text NA into SQL NULL, and dateFormat uses the day-first pattern so dates parse correctly.
Exercise
You load a folder of pretty-printed JSON files, each containing one object spread over many lines, using FILEFORMAT = JSON with no options. Every row comes back as a parse failure. What is wrong, and what fixes it?
Show answer
The JSON reader expects one complete object per line by default, so a multi-line object is split into fragments that are not valid JSON. Add 'multiLine' = 'true' to FORMAT_OPTIONS so the reader treats each file's content as a whole document.