Skip to content

Export a query to CSV

This recipe writes the result of a query to a CSV file. CSV is comma-separated values, with the names of the columns on the first line. The examples use a SQLite file, shop.db, with a table products.

Write the products of a SQLite file to a CSV file from the shell, and look at the file.

-C (--csv) prints the result as CSV. Send it to a file:

Terminal window
usql -C -c 'select id, name, price from products order by id' shop.db > products.csv

The file holds the rows and nothing else:

id,name,price
1,"Green tea",3.75
2,"Coffee beans",12.25
3,Cocoa,5.25

usql writes no banner and no row count into the file. It puts a value that holds a space, a comma or a quote between double quotes. To leave out the line of the column names, add -t.

-o writes to the file in place of the standard output:

Terminal window
usql -C -o products.csv -c 'select id, name, price from products order by id' shop.db

To export a long query, keep it in a file, and run the file with -f:

Terminal window
usql -C -o products.csv -f products.sql shop.db

At the prompt, end the query with \g, the format in parentheses, and the name of the file:

select id, name, price from products order by id \g (format=csv) products.csv

The format applies only to this query. To write more queries to one file, set the format and the output first:

\pset format csv
\o products.csv
select id, name, price from products order by id;
\o

\o with no file sends the output back to the terminal. The format stays csv until you change it with \pset format aligned.

-F sets the separator of the fields. This command writes values separated by tabs:

Terminal window
usql -C -F $'\t' -c 'select id, name from products' shop.db > products.tsv

Format the output explains the formats and the print options.