sql2csv1
Sql2csv documentation
Overview
Executes arbitrary commands against a SQL database and outputs the results as a CSV:
usage: sql2csv [-h] [-v] [-l] [-V] [--db CONNECTION_STRING] [--query QUERY][-e ENCODING] [-H][FILE]Execute a SQL query on a database and output the result to a CSV file.positional arguments:FILE The file to use as the SQL query. If FILE and --queryare omitted, the query is piped data via STDIN.optional arguments:-h, --help show this help message and exit--db CONNECTION_STRINGA SQLAlchemy connection string to connect to adatabase.--engine-option ENGINE_OPTION ENGINE_OPTIONA keyword argument to SQLAlchemy's create_engine(), asa space-separated pair. This option can be specifiedmultiple times. For example: thick_mode True--execution-option EXECUTION_OPTION EXECUTION_OPTIONA keyword argument to SQLAlchemy'sexecution_options(), as a space-separated pair. Thisoption can be specified multiple times. For example:stream_results True--query QUERY The SQL query to execute. Overrides FILE and STDIN.-e ENCODING, --encoding ENCODINGSpecify the encoding of the input query file.-H, --no-header-row Do not output column names.
Examples
Load sample data into a table using csvsql and then query it using sql2csv:
csvsql --db "sqlite:///dummy.db" --tables "test" --insert examples/dummy.csvsql2csv --db "sqlite:///dummy.db" --query "select * from test"
Load data about financial aid recipients into PostgreSQL. Then find the three states that received the most, while also filtering out empty rows:
createdb recipientscsvsql --db "postgresql:///recipients" --tables "fy09" --insert examples/realdata/FY09_EDU_Recipients_by_State.csvsql2csv --db "postgresql:///recipients" --query "select * from fy09 where \"State Name\" != '' order by fy09.\"TOTAL\" limit 3"
You can even use it as a simple SQL calculator (in this example an in-memory SQLite database is used as the default):
sql2csv --query "select 300 * 47 % 14 * 27 + 7000"
The connection string accepts parameters. For example, to set the encoding of a MySQL database:
sql2csv --db 'mysql://user:pass@host/database?charset=utf8' --query "SELECT myfield FROM mytable"
History
- Arch Linux 2026-11-01: the text shown here
- Debian 13 (Trixie)
- Debian 12 (Bookworm)
- Debian 11 (Bullseye)
--db until Debian 12 (Bookworm);
--encoding until Debian 12 (Bookworm);
--help until Debian 12 (Bookworm);
--linenumbers until Debian 12 (Bookworm);
--no-header-row until Debian 12 (Bookworm);
--query until Debian 12 (Bookworm);
--verbose until Debian 12 (Bookworm);
--version until Debian 12 (Bookworm);
-H until Debian 12 (Bookworm);
-V until Debian 12 (Bookworm);
-e until Debian 12 (Bookworm);
-h until Debian 12 (Bookworm);
-l until Debian 12 (Bookworm);
-v until Debian 12 (Bookworm).