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.
From the shell
Section titled “From the shell”-C (--csv) prints the result as CSV. Send it to a file:
usql -C -c 'select id, name, price from products order by id' shop.db > products.csvThe file holds the rows and nothing else:
id,name,price1,"Green tea",3.752,"Coffee beans",12.253,Cocoa,5.25usql 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:
usql -C -o products.csv -c 'select id, name, price from products order by id' shop.dbTo export a long query, keep it in a file, and run the file with -f:
usql -C -o products.csv -f products.sql shop.dbFrom the prompt
Section titled “From the prompt”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.csvThe 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.csvselect 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.
Another separator
Section titled “Another separator”-F sets the separator of the fields. This command writes values separated by tabs:
usql -C -F $'\t' -c 'select id, name from products' shop.db > products.tsvFormat the output explains the formats and the print options.