Sub topic 6
NULLs, empty strings, and quoting
This chapter covers how COPY in CSV mode tells a missing value (NULL) apart from an empty string, and how quoting protects delimiters, quotes, and line breaks inside fields. It assumes you can already run COPY ... FROM and COPY ... TO with FORMAT csv and HEADER, and that you know the products table from earlier chapters. You should also know that a NULL in SQL means "no value" and is not the same thing as ''.
Why this matters
A CSV file has no type system. It is only text separated by commas, so COPY needs rules to decide which fields become NULL and which become strings. If the rules do not match your file, you get one of three outcomes:
- The load fails with an error such as
invalid input syntax for type date: "". - The load fails with
null value in column "name" violates not-null constraint. - The load succeeds but silently stores empty strings where you wanted NULLs, or the reverse.
The third outcome is the dangerous one, because queries like WHERE notes IS NULL then return wrong results.
The default rules in CSV format
In CSV format, COPY uses these defaults:
- The NULL string is an unquoted empty string. A field with nothing between two delimiters is NULL.
- An empty string is a quoted empty string, written
"". - A field is quoted with the
QUOTEcharacter, which is"by default. - A quote character inside a quoted field is written twice (
""), becauseESCAPEdefaults to the same character asQUOTE. - A quoted field may contain the delimiter and line breaks, so one record can span several lines.
The following script loads four rows that exercise each rule. It uses FROM STDIN, so the data sits inline in the psql script and you can run it as shown. The chapter on server-side COPY versus \copy explains STDIN.
TRUNCATE products;
COPY products (id, name, price, released, notes) FROM STDIN WITH (FORMAT csv);
1,Widget,9.99,2024-01-15,
2,Gadget,19.50,2024-02-01,""
3,"Gizmo, large",24.00,,"Says ""new"" on the box"
4,"Two
lines",5.00,2024-03-10,NULL
\.
SELECT id,
notes IS NULL AS notes_is_null,
length(notes) AS notes_len,
released IS NULL AS released_is_null
FROM products
ORDER BY id;The query returns this:
id | notes_is_null | notes_len | released_is_null
----+---------------+-----------+------------------
1 | t | | f
2 | f | 0 | f
3 | f | 21 | t
4 | f | 4 | f
(4 rows)Here is how each row was read:
- Row 1:
notesis empty and unquoted, so it is NULL. - Row 2:
notesis"", so it is an empty string with length 0. It is not NULL. - Row 3:
releasedis empty and unquoted, so it is NULL. The nameGizmo, largekeeps its comma because it is quoted. The doubled quotes innotescollapse to single quotes, givingSays "new" on the box. - Row 4: The name contains a line break inside quotes, so it is one record. The
notesvalueNULLis the four-letter string, because the default NULL string is the empty string and not the wordNULL.
How a field is classified on input
The following diagram shows the decision COPY FROM makes for each field in CSV mode. The FORCE_NULL and FORCE_NOT_NULL options are covered in the next sections.
The last step matters. Any non-NULL value is converted to the column's type. An empty string cannot be converted to date or numeric, so a quoted "" in a date column is an error, not a NULL.
Changing the NULL string
Many tools write the word NULL (or \N, or N/A) for missing values. The NULL option sets the string that means NULL:
\copy products FROM 'products.csv' WITH (FORMAT csv, HEADER true, NULL 'NULL')Once you set NULL 'NULL', two things change:
- An unquoted
NULLbecomes a database NULL. - An unquoted empty field is no longer NULL. It becomes an empty string for text columns. For a
dateornumericcolumn it raises an error.
The second point is the usual cause of "it worked with the default but fails now". If your file uses both conventions, empty cells for some columns and NULL for others, a single NULL option cannot cover both. Load it into a staging table with all columns as text and convert there.
Quoting also protects a real string that happens to match the NULL string. With NULL 'NULL', the field NULL is NULL and the field "NULL" is the four-letter string.
Overriding the rules per column
Two options adjust the rules for named columns. Both work only with COPY FROM in CSV format.
| Option | Effect | Typical use |
|---|---|---|
| `FORCE_NULL (col, ...)` | A value equal to the NULL string becomes NULL even when it is quoted. | A tool writes `""` for missing dates and numbers. |
| `FORCE_NOT_NULL (col, ...)` | A value is never matched against the NULL string, so an empty field becomes an empty string. | You want empty cells in a text column stored as `''`. |
This example handles a file where a careless exporter quotes everything, so missing dates arrive as "":
\copy products (id, name, price, released, notes) FROM 'products.csv' WITH (FORMAT csv, HEADER true, FORCE_NULL (price, released))Without FORCE_NULL, a "" in released fails with invalid input syntax for type date: "". With it, the quoted empty string becomes NULL in price and released. The notes column is still read by the normal rules, so "" there stays an empty string.
The opposite case is a text column where you want '' and not NULL:
\copy products (id, name, price, released, notes) FROM 'products.csv' WITH (FORMAT csv, HEADER true, FORCE_NOT_NULL (notes))Do not put FORCE_NOT_NULL on a date or numeric column unless the file never has empty values there. An empty field would be treated as the string '', and the conversion would fail.
How NULLs and empty strings are written on export
COPY TO in CSV format follows the same conventions in reverse:
- A NULL is written as the NULL string, never quoted. By default that is nothing at all.
- An empty string is written as
"", so it can be told apart from a NULL. - A string is quoted only when it needs to be: it contains the delimiter, the quote character, a line break, or a carriage return. A string that equals the NULL string is also quoted, so it cannot be mistaken for a NULL.
Exporting the four rows loaded earlier shows this:
COPY products TO STDOUT WITH (FORMAT csv, HEADER true);id,name,price,released,notes
1,Widget,9.99,2024-01-15,
2,Gadget,19.50,2024-02-01,""
3,"Gizmo, large",24.00,,"Says ""new"" on the box"
4,"Two
lines",5.00,2024-03-10,NULLThis output is the same as the input. The export keeps the distinction between row 1 (NULL) and row 2 (empty string), so loading it back with the same options reproduces the table.
If you export with NULL 'NULL', the result changes in row 4. The string NULL in notes is now quoted as "NULL", and a real NULL is written as bare NULL:
COPY products (id, notes) TO STDOUT WITH (FORMAT csv, NULL 'NULL');For this output, load with the same NULL 'NULL' option, and the quoted "NULL" stays a string.
Forcing quotes on output
Some consumers want certain columns always quoted. FORCE_QUOTE does that for COPY TO:
\copy products TO 'products_quoted.csv' WITH (FORMAT csv, HEADER true, FORCE_QUOTE (name, notes))FORCE_QUOTE * quotes every non-NULL value in every column. NULLs are never quoted, whatever the option says. This is why a quoted-everything file can still distinguish NULL from "".
Choosing quote and escape characters
The defaults work for standard CSV. Two options change them:
QUOTE 'x'sets the quote character. It must be a single one-byte character and must differ from the delimiter.ESCAPE 'x'sets the character that precedes a quote character inside a quoted value. It defaults to theQUOTEcharacter, which gives the doubled-quote convention ("").
Some producers escape quotes with a backslash instead of doubling them. A field such as "Says \"new\"" needs the following:
\copy products FROM 'products.csv' WITH (FORMAT csv, HEADER true, ESCAPE '\')With ESCAPE '\', a backslash followed by a quote is read as a literal quote. A backslash followed by anything else is kept as a literal backslash. On export, the same option makes COPY TO write \" instead of "".
Contrast with text format
If you omit FORMAT csv, COPY uses the default text format. Its rules differ:
| Aspect | `FORMAT csv` | Text format (default) |
|---|---|---|
| Default delimiter | comma | tab |
| Default NULL string | unquoted empty string | `\N` |
| Empty string | `""` | an empty field |
| Quoting | `QUOTE` character | none; special characters use backslash escapes (`\t`, `\n`, `\\`) |
In text format an empty field is an empty string, and NULL must be \N. Mixing the two formats is a common source of errors. A file with \N for missing values loaded as CSV produces the literal two-character string \N, or an error in a numeric column. For a \N file you must either use text format or write NULL '\N' with CSV.
A checklist for matching a file to COPY
When you receive a new file, answer these questions before you load it:
- How does the file mark a missing value: an empty cell, the word
NULL,\N, or something else? SetNULLaccordingly. - Does it also use
""for missing values in non-text columns? If so, addFORCE_NULLfor those columns. - Should empty cells in text columns be
''and not NULL? If so, addFORCE_NOT_NULL. - Are quotes doubled or backslash-escaped? Set
ESCAPEif they are escaped. - Do any fields contain line breaks? CSV handles them if they are quoted, but a line-based tool such as
wc -lwill count more lines than rows. - Are the
NOT NULLcolumns in the table always filled in the file? An empty field inproducts.namefails with a not-null violation, and the whole load is rolled back.
If the answers are unclear or mixed, load everything into a staging table with text columns, inspect it with queries such as SELECT count(*) FROM staging WHERE notes = '', and convert with NULLIF(notes, '') when you move the data into the real table.
Exercise
A CSV file written by another tool has the header id,name,price,released,notes. In it, missing prices appear as "" (a quoted empty string) and missing release dates appear as an unquoted empty field. You load it with WITH (FORMAT csv, HEADER true) and get invalid input syntax for type numeric: "". What change to the COPY options fixes the load, and what does released become for the rows with an empty field?
Show answer
Add FORCE_NULL (price) so a quoted empty string in price is converted to NULL, for example WITH (FORMAT csv, HEADER true, FORCE_NULL (price)). Without it, the quoted "" is a non-NULL empty string, and an empty string cannot be converted to numeric. The unquoted empty released fields are already NULL under the default CSV rules, so they need no option.
Exercise
You export products with COPY products TO STDOUT WITH (FORMAT csv, NULL 'NULL'). One row has a notes value that is the four-letter string NULL, and another row has a notes value that is a real NULL. How do the two appear in the output, and how do you load the file back so that both are restored correctly?
Show answer
The string value is written quoted, as "NULL", and the real NULL is written unquoted, as NULL. Load the file with the same NULL 'NULL' option, for example COPY products FROM STDIN WITH (FORMAT csv, NULL 'NULL'). The unquoted NULL becomes a database NULL, and the quoted "NULL" stays the string.