Skip to content
shellhacks.dev
Databases

Export SQLite Query Results as CSV from the Shell

Export a query as CSV with sqlite3 -csv -header db 'select ...'. Fields with commas or quotes are quoted correctly, and NULL becomes an empty field.

1 min read
Summarize in AI

You want query results in a spreadsheet-friendly form, with the column names in the first row.

Shell
sqlite3 app.db <<'SQL'
create table t(name text, note text);
insert into t values ('Smith, J', 'said "hi"'), ('Lee', NULL);
SQL
sqlite3 -csv -header app.db 'select * from t'
Text
name,note
"Smith, J","said ""hi"""
Lee,

The -csv option sets the output mode to comma-separated values and -header turns on the column titles. The shell applies the rules of RFC 4180: a field with a comma or a quote is wrapped in double quotes and inner quotes are doubled, as in the first row, so the file loads correctly elsewhere. NULL has no representation in CSV and is written as an empty field. The options are in the sqlite3 command line shell documentation.

The empty field cannot be told from an empty string, so set .nullvalue if the difference matters. To write straight to a file, use .once file.csv before the query inside the shell, or redirect the output. Embedded newlines stay inside the quoted field and break tools that split on lines. The separator is changed with -separator.

Taggedcsvsqlite
Share

More snippets

Databases

Import a CSV File into SQLite with .import

Load a CSV with sqlite3 .import --csv file table. If the table already exists the header row is inserted as data unless you add --skip 1 (3.32 or later).

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.