usql

CLI

Universal psql-style SQL command line: one tool to connect to PostgreSQL, MySQL, SQLite, SQL Server, Oracle and dozens of other SQL and NoSQL databases, with support for copying data between databases.

xo/usql10.2k
README

usql is a universal command-line interface for PostgreSQL, MySQL, Oracle Database, SQLite3, Microsoft SQL Server, and many other databases including NoSQL and non-relational databases!

usql works with SQL and NoSQL databases from a command line modelled on PostgreSQL's psql. usql supports most of the core psql features, such as variables, backticks, backslash commands and has additional features that psql does not, such as multiple database support, copying between databases, context-based completion, and terminal graphics.

Database administrators and developers that would prefer to work with a tool like psql with non-PostgreSQL databases, will find usql intuitive, easy-to-use, and a great replacement for the command-line clients/tools for other databases.

The documentation of usql, with guides and a reference, is at usql.app.

Unit Tests Go Reference Releases Discord Discussion

Installing

usql can be installed via Release, via Homebrew, via AUR, via Go or via Docker:

Installing via Release

  1. Download a release for your platform
  2. Extract the usql or usql.exe file from the .tar.bz2 or .zip file
  3. Move the extracted executable to somewhere on your $PATH (Linux/macOS) or %PATH% (Windows)

Each archive also holds three man pages. usql.1 is the command line, usql-commands.1 is the meta commands and the variables, and usqlrc.5 is the configuration files. On Linux and macOS, copy usql.1 and usql-commands.1 to /usr/local/share/man/man1, and usqlrc.5 to /usr/local/share/man/man5. Then man usql, man usql-commands and man usqlrc show them.

The Windows Package Manager (winget) does not have usql yet. When the package usql.usql is published there, this command installs usql:

# install usql, once the package is published
winget install usql.usql

Installing via Homebrew (macOS and Linux)

Install usql from the xo/xo tap in the usual way with the brew command:

# install usql
$ brew install xo/xo/usql

usql includes the driver for ODBC databases, and the formula needs no option for it. To connect through ODBC, install an ODBC driver manager, such as unixodbc, and the ODBC driver of your database.

Installing via AUR (Arch Linux)

Install usql from the Arch Linux AUR in the usual way with the yay command:

# install usql
$ yay -S usql-bin

usql-bin installs the released binary. To build from source instead, use the usql package, which takes considerably longer because it compiles every driver:

# build usql from source
$ yay -S usql

Alternately, build and install using makepkg:

$ git clone https://aur.archlinux.org/usql.git && cd usql
$ makepkg -si

Installing via Go

Install usql in the usual Go fashion:

# install the latest usql version, with every driver
$ go install github.com/xo/usql@latest

See below for information on the build tags that leave drivers out.

Installing via Docker

An official container image (docker.io/usql/usql) is maintained by the usql team, and can be used with Docker, Podman, or other container runtime.

Install usql with Docker, Podman, or other container runtime:

# run interactive shell and mount the $PWD/data directory as a volume for use
# within the container
$ docker run --rm -it --volume $(pwd)/data:/data docker.io/usql/usql:latest sqlite3://data/test.db
Trying to pull docker.io/usql/usql:latest...
Getting image source signatures
Copying blob af48168d69d8 done   |
Copying blob efc2b5ad9eec skipped: already exists
Copying config 917ceb411d done   |
Writing manifest to image destination
Connected with driver sqlite3 (SQLite3 3.45.1)
Type "help" for help.

sq:data/test.db=> \q

# run postgres locally
$ docker run --detach --rm --name=postgres --publish=5432:5432 --env=POSTGRES_PASSWORD=P4ssw0rd docker.io/usql/postgres

# connect to local postgres instance
$ docker run --rm --network host -it docker.io/usql/usql:latest postgres://postgres:P4ssw0rd@localhost
Connected with driver postgres (PostgreSQL 16.3 (Debian 16.3-1.pgdg120+1))
Type "help" for help.

pg:postgres@localhost=> \q

# run specific usql version
$ docker run --rm -it docker.io/usql/usql:0.21.5

Building

usql has one build. A go build or go install with no build tags includes every driver, except the opt-in drivers, and the chart renderer:

# build/install with every driver except the opt-in drivers
$ go install github.com/xo/usql@main

Each driver has a build tag, which the table of drivers lists in its Scheme / Tag column. The build tag no_<tag> leaves that driver out:

# build/install every driver except Avatica, Couchbase and PostgreSQL
$ go install -tags 'no_avatica no_couchbase no_postgres' github.com/xo/usql@main

The build tag no_drivers leaves out every driver. Name a driver by its tag to put it back:

# build/install with only the SQLite3 driver
$ go install -tags 'no_drivers sqlite3' github.com/xo/usql@main

# build/install with only the PostgreSQL and MySQL drivers
$ go install -tags 'no_drivers pgx mysql' github.com/xo/usql@main

no_drivers also leaves out the chart renderer. Add the tag charts to keep it. The tag no_charts leaves it out of any build.

The table of drivers marks the opt-in drivers with ‡. A build includes an opt-in driver only when it names the tag of that driver, with or without no_drivers. The release builds of usql do not include them. Each opt-in driver changes the global state of the process when it loads, and usql does not permit that. Each one leaves usql if its upstream project does not fix this.

# build/install with every driver and the opt-in VoltDB driver
$ go install -tags voltdb github.com/xo/usql@main

# build/install with only the opt-in SAP HANA driver
$ go install -tags 'no_drivers saphana' github.com/xo/usql@main

Database Support

usql works with all Go standard library compatible SQL drivers supported by github.com/xo/dburl.

The list of drivers that usql was built with can be displayed with the \drivers command:

$ cd $GOPATH/src/github.com/xo/usql

# build with only the cassandra, moderncsqlite and mysql drivers
$ go build -tags 'no_drivers cassandra moderncsqlite mysql'

# show built driver support
$ ./usql -c '\drivers'
Available Drivers:
  cassandra [ca, cql, scy, cass, scylla, datastax]
  moderncsqlite [mq, sq, sqlite, sqlite3, modernsqlite]
  mysql [my, maria, aurora, mariadb, percona]

The above shows that usql was built with only the cassandra, moderncsqlite and mysql drivers. Each line names the scheme of a driver, and its aliases in [...]. Without sqlite3, moderncsqlite also answers to the sqlite3 scheme and its aliases.

Supported Database Schemes and Aliases

The following are the Go SQL drivers that usql supports, the associated database, scheme / build tag, and scheme aliases:

DatabaseScheme / TagScheme AliasesDriver Package / Notes
PostgreSQLpgxpostgres, pg, pgsql, postgresql, pxgithub.com/jackc/pgx/v5/stdlib
MySQLmysqlmy, maria, aurora, mariadb, perconagithub.com/go-sql-driver/mysql
Microsoft SQL Serversqlserverms, mssql, azuresqlgithub.com/microsoft/go-mssqldb
Oracle Databaseoracleor, ora, oci, oci8, odpi, odpi-cgithub.com/xo/oracle
SQLite3sqlite3sq, sqlite, filegithub.com/mattn/go-sqlite3 † §
DuckDBduckdbdk, ddb, duck, filegithub.com/duckdb/duckdb-go/v2 † §
Alibaba MaxComputemaxcomputemcgithub.com/xo/dbimp/maxcompute
Alibaba Tablestoretablestoreot, otsgithub.com/xo/dbimp/tablestore
Amazon Athenaathenas3, aws, awsathenagithub.com/xo/dbimp/athena
Amazon Redshiftredshiftrsgithub.com/jackc/pgx/v5/stdlib
Apache Avaticaavaticaav, phoenixgithub.com/xo/dbimp/avatica
Apache Drilldrilldlgithub.com/xo/dbimp/drill
Apache Druiddruiddrgithub.com/xo/dbimp/druid
Apache Hivehivehi, hive2github.com/xo/dbimp/hive
Apache Impalaimpalaimgithub.com/xo/dbimp/hive
Apache Pinotpinotpigithub.com/xo/dbimp/pinot
Apache Solrsolrsogithub.com/xo/dbimp/solr
ArangoDBarangodbar, arangogithub.com/xo/dbimp/arangodb
Azure Cosmos DBcosmoscmgithub.com/xo/dbimp/cosmos
Cassandracassandraca, cql, scy, cass, scylla, datastaxgithub.com/xo/cassandra
ChaiSQLchaici, genji, chaisqlgithub.com/chaisql/chai § ‡
ClickHouseclickhousechgithub.com/xo/dbimp/clickhouse
CockroachDBcockroachdbcr, cdb, crdb, cockroachgithub.com/jackc/pgx/v5/stdlib
Couchbasecouchbasen1, n1qlgithub.com/xo/dbimp/couchbase
CrateDBcratedbct, crategithub.com/jackc/pgx/v5/stdlib
CSVQcsvqcs, csv, tsv, jsongithub.com/mithrandie/csvq-driver §
Databenddatabenddd, bendgithub.com/xo/dbimp/databend
Databricksdatabricksbr, brick, bricks, databrickgithub.com/xo/dbimp/databricks
DynamoDBdynamodbdy, dyn, dynamogithub.com/xo/dbimp/dynamodb
Elasticsearchelasticsearches, elasticgithub.com/xo/dbimp/elasticsearch
Exasolexasolex, exagithub.com/xo/dbimp/exasol
Firebirdfirebirdfb, firebirdsqlgithub.com/nakagami/firebirdsql
FlightSQLflightsqlfl, flightgithub.com/apache/arrow-go/v18/arrow/flight/flightsql/driver ‡
Google BigQuerybigquerybqgithub.com/xo/dbimp/bigquery
Google Spannerspannerspgithub.com/xo/dbimp/spanner
InfluxDBinfluxdbin, influxgithub.com/xo/dbimp/influxdb
InfluxDB InfluxQLinfluxqliqgithub.com/xo/dbimp/influxdb
libSQLlibsqlls, tursogithub.com/xo/dbimp/libsql
ModernC SQLite3moderncsqlitemq, modernsqlitemodernc.org/sqlite §
Neo4jneo4jnj, neo, n4jgithub.com/xo/dbimp/neo4j
ODBCodbcodgithub.com/xo/odbc
OpenSearchopensearchos, opengithub.com/xo/dbimp/opensearch
PostgreSQL lib/pqlibpqpqgithub.com/lib/pq
Prestoprestopr, prestodbgithub.com/xo/dbimp/trino
QuestDBquestdbqsgithub.com/jackc/pgx/v5/stdlib
rqliterqliterqgithub.com/xo/dbimp/rqlite
SAP HANAsaphanasa, sap, hana, hdbgithub.com/SAP/go-hdb/driver ‡
SingleStore MemSQLmemsqlmegithub.com/go-sql-driver/mysql
Snowflakesnowflakesfgithub.com/xo/dbimp/snowflake
SurrealDBsurrealdbsr, sur, surrealgithub.com/xo/dbimp/surrealdb
TiDBtidbtigithub.com/go-sql-driver/mysql
Trinotrinotrgithub.com/xo/dbimp/trino
Verticaverticavegithub.com/vertica/vertica-sql-go
Vitess Databasevitessvtgithub.com/go-sql-driver/mysql
VoltDBvoltdbvo, vdb, voltgithub.com/VoltDB/voltdb-client-go/voltdbclient ‡
YDBydbydgithub.com/ydb-platform/ydb-go-sdk/v3 ‡
NO DRIVERSno_driversleave out every driver that is not named by its tag
NO <TAG>no_<tag>leave out the driver with <tag>

† Requires CGO
§ Embedded, with no server to run
Hosted service, with no server you can run
‡ Opt-in: only a build that names its tag includes it

Any of the protocol schemes/aliases above can be used in conjunction when connecting to a database via the command-line or with the \connect and \copy commands:

# connect to a vitess database:
$ usql vt://user:pass@host:3306/mydatabase

$ usql
(not connected)=> \c vitess://user:pass@host:3306/mydatabase

$ usql
(not connected)=> \copy csvq://. pg://localhost/ 'select * ....' 'myTable'

See the section below on connecting to databases for further details building DSNs/URLs for use with usql.

Using

After installing, usql can be used similarly to the following:

# connect to a postgres database
$ usql postgres://booktest@localhost/booktest

# connect to an oracle database
$ usql oracle://user:pass@host/oracle.sid

# connect to a postgres database and run the commands contained in script.sql
$ usql pg://localhost/ -f script.sql

Command-line Options

Supported command-line options:

$ usql --help
usql, the universal command-line interface for SQL databases

Usage:
  usql [OPTION]... [DSN]

General options:
  -c, --command=COMMAND    run only single command (SQL or internal) and exit
  -d, --dbname=DSN         database url or connection name to connect to
  -f, --file=FILE          execute commands from file, then exit
  -l, --list               list available databases, then exit
  -v, --set=, --variable=NAME=VALUE
                           set script variable NAME to VALUE (see \set command)
  -O, --option=NAME=VALUE  set configuration option NAME (SECTION.NAME) to VALUE (see \config command)
  -U, --uset=NAME=VALUE    set setting NAME of usql to VALUE (see \uset command)
  -N, --cset=NAME=DSN      set named connection NAME to DSN (see \cset command)
  -D, --dump               write the database as a usql script to standard output or to the file of -o, then exit
      --config=FILE        config file
  -V, --version            output version information, then exit
  -X, --no-init            do not execute initialization scripts
  -1, --single-transaction
                           execute as a single transaction (if non-interactive)
  -?, --help[=options]     show this help, then exit
      --help=commands      list backslash commands, then exit
      --help=variables     list variables and settings, then exit

Input and output options:
  -a, --echo-all           echo all input from script
  -b, --echo-errors        echo failed commands
  -e, --echo-queries       echo commands sent to server
  -E, --echo-hidden        display queries that internal commands generate
  -o, --output=FILE        send query results to file
  -q, --quiet              run quietly (no messages, only query output)

Output format options:
  -A, --no-align           unaligned table output mode
  -C, --csv                CSV output mode
  -F, --field-separator=STRING
                           field separator for unaligned and CSV output (default "|" and ",")
  -G, --vertical           vertical output mode
  -H, --html               HTML table output mode
  -J, --json               JSON output mode
  -M, --markdown           markdown output mode
  -P, --pset=VAR=ARG       set printing option VAR to ARG (see \pset command)
  -R, --record-separator=STRING
                           record separator for unaligned and CSV output (default \n)
  -t, --tuples-only        print rows only
  -T, --table-attr=TEXT    set HTML table tag attributes (e.g., width, border)
  -x, --expanded           turn on expanded table output
  -z, --field-separator-zero
                           set field separator for unaligned and CSV output to zero byte
  -0, --record-separator-zero
                           set record separator for unaligned and CSV output to zero byte

Connection options:
  -w, --no-password        never prompt for password
  -W, --password           force password prompt (should happen automatically)

For more information, type "\?" (for internal commands) or "\help" (for SQL
commands) from within usql, or see https://github.com/xo/usql.

Connecting to Databases

usql opens a database connection by parsing a URL and passing the resulting connection string to a database driver. Database connection strings (aka "data source name" or DSNs) have the same parsing rules as URLs, and can be passed to usql via command-line, or to the \connect, \c, and \copy commands.

Database connections can be defined with the \cset command or in the config.yaml configuration file.

Database Connection Strings

Database connection strings look like the following:

  driver+transport://user:pass@host/dbname?opt1=a&opt2=b
  driver:/path/to/file
  /path/to/file
  name

Where the above are:

ComponentDescription
driverdriver scheme name or scheme alias
transporttcp, udp, unix or driver name (for ODBC and ADODB)
userusername
passpassword
hosthostname
dbname ±database name, instance, or service name/ID
?opt1=a&...additional database driver options (see respective SQL driver for available options)
/path/to/filea path on disk
namea connection name set by \cset or in config.yaml

± Some databases, such as Microsoft SQL Server, or Oracle Database support a path component (ie, /dbname) in the form of /instance/dbname, where /instance is the optional service identifier (aka "SID") or database instance

Driver Aliases

usql supports the same driver names and aliases as the dburl package. Databases have at least one or more aliases. See dburl's scheme documentation for a list of all supported aliases.

Short Aliases

All database drivers have a short form of 2 characters, which is usually the first 2 letters of the database driver. For example, pg for postgres, my for mysql, ms for sqlserver, or for oracle, or sq for sqlite3.

Passing Driver Options

Driver options are specified as standard URL query options in the form of ?opt1=a&opt2=b. Refer to the relevant database driver's documentation for available options.

Paths on Disk

If a URL does not have a driver: scheme, usql will check if it is a path on disk. If the path exists, usql will attempt to use an appropriate database driver to open the path.

When the path is a Unix Domain Socket, usql will attempt to open it with the MySQL driver. When the path is a directory, usql will attempt to open it using the PostgreSQL driver. And, lastly, when the path is a regular file, usql will attempt to open the file using the SQLite3 or DuckDB drivers.

Driver Defaults

As with URLs, most components in the URL are optional and many components can be left out. usql will attempt connecting using defaults where possible:

# connect to postgres using the local $USER and the unix domain socket in /var/run/postgresql
$ usql pg://

See the relevant documentation on database drivers for more information.

The USQL_DSN Environment Variable

When the command line names no DSN, usql opens the DSN in the USQL_DSN environment variable. A program or a script that holds a password can use it to keep the password out of the argument list, which every user of the machine can read:

$ USQL_DSN="pg://app:$PASSWORD@localhost:15432/app" usql

The variable holds a full DSN or the name of a connection. A DSN on the command line wins, and usql then does not read the variable. usql removes the variable from its own environment after it reads it, so that \!, the pager and the editor do not get the password. \c never reads the variable.

usql has no environment variable for the password alone.

Databases in Kubernetes

usql opens a database that runs in Kubernetes through a port forward. The dbfwd package finds the database and its credentials, and runs kubectl port-forward to it. kubectl must be on the PATH, and it uses the current context of the kubeconfig, or the one that ?context= names:

# the Service, StatefulSet or pod pg in the namespace prod
$ usql k://pg.prod/app

# the CloudNativePG cluster pg, with another context
$ usql 'k8s+cnpg://pg.prod/app?context=staging'

The URL holds no password. dbfwd reads it from the Secret of the operator or of the pod, so -W does not apply. The banner and \conninfo name what the forward reached, such as Service pg-rw in context kind-prod, namespace prod, owned by CloudNativePG Cluster pg, and the prompt shows the host from the URL, such as pg, in place of the local address and port. When the pod restarts, the forward follows it, and the first statement after that fails as it does after a server restart. When no pod runs for two minutes, the forward is lost, and \c with no argument starts it again.

\k lists the databases that usql can reach, with the URL that \c opens:

=> \k -A
    List of Kubernetes databases in context kind-prod, every namespace
 Namespace | Name |   Type   |  Kind   |     Operator     |      URL
-----------+------+----------+---------+------------------+----------------
 prod      | pg   | postgres | Cluster | CloudNativePG    | k://pg.prod/
 prod      | shop | mariadb  | MariaDB | mariadb-operator | k://shop.prod/
(2 rows)

\k lists the current namespace, -A every namespace, -n NAMESPACE one namespace, and --context NAME another context. A scope narrows the list, such as pg*, pg*.prod or cnpg://*, and its k:// is optional. Only * is a wildcard. \k+ adds the roles, the ready pods, the databases, and where the password comes from. \k reads no Secret.

On Linux and FreeBSD, if usql is killed, kubectl stops with it. On other systems, a kubectl port-forward can keep running after usql is killed with SIGKILL, and it must be stopped by hand.

See dbfwd's URL rules for the types and the parts of the URL, and its lookup rules for how it finds a database from a name.

Connection Examples

The following are example connection strings and additional ways to connect to databases using usql:

# connect to a postgres database
$ usql pg://user:pass@host/dbname
$ usql pgsql://user:pass@host/dbname
$ usql postgres://user:pass@host:port/dbname
$ usql pg://
$ usql /var/run/postgresql
$ usql pg://user:pass@host/dbname?sslmode=disable # Connect without SSL

# connect to a mysql database
$ usql my://user:pass@host/dbname
$ usql mysql://user:pass@host:port/dbname
$ usql my://
$ usql /var/run/mysqld/mysqld.sock

# connect to a sqlserver database
$ usql sqlserver://user:pass@host/instancename/dbname
$ usql ms://user:pass@host/dbname
$ usql ms://user:pass@host/instancename/dbname
$ usql mssql://user:pass@host:port/dbname
$ usql ms://

# connect to a sqlserver database using Windows domain authentication
$ runas /user:ACME\wiley /netonly "usql mssql://host/dbname/"

# connect to a oracle database
$ usql or://user:pass@host/sid
$ usql oracle://user:pass@host:port/sid
$ usql or://

# connect to a cassandra database
$ usql ca://user:pass@host/keyspace
$ usql cassandra://host/keyspace
$ usql cassandra://host/
$ usql ca://

# connect to an alibaba maxcompute project over https, or over http with tls=false:
$ usql "mc://accessid:accesskey@service.cn-hangzhou.maxcompute.aliyun.com/myproject"
$ usql "mc://accessid:accesskey@host/myproject?region=cn-hangzhou&tls=false"

# connect to an alibaba tablestore instance, where the host
# myinstance.cn-hangzhou becomes myinstance.cn-hangzhou.ots.aliyuncs.com:
$ usql "tablestore://accessid:accesssecret@myinstance.cn-hangzhou/myinstance"

# connect to a sqlite database that exists on disk
$ usql dbname.sqlite3

# Note: when connecting to a SQLite database, if the "driver://" or
# "driver:" scheme/alias is omitted, the file must already exist on disk.
#
# if the file does not yet exist, the URL must incorporate file:, sq:, sqlite3:,
# or any other recognized sqlite3 driver alias to force usql to create a new,
# empty database at the specified path:
$ usql sq://path/to/dbname.sqlite3
$ usql sqlite3://path/to/dbname.sqlite3
$ usql file:/path/to/dbname.sqlite3

# connect to a named connection in config.yaml (see Configuration below for
# where it is on each system)
$ cat $HOME/.config/usql/config.yaml
connections:
  my_named_connection: sqlserver://user:pass@localhost/
$ usql my_named_connection

# connect with ODBC driver (needs the ODBC driver manager of the system)
$ cat /etc/odbcinst.ini
[PostgreSQL ANSI]
Description=PostgreSQL ODBC driver (ANSI version)
Driver=psqlodbca.so
Setup=libodbcpsqlS.so
Debug=0
CommLog=1
UsageCount=1

# connect to a postgres database using the odbc config above
$ usql odbc+PostgreSQL+ANSI://user:pass@localhost/dbname?TraceFile=/path/to/trace.log

See the section on connection variables for information on defining connection names.

Executing Queries and Commands

The interactive interpreter reads queries and backslash meta (\) commands, sending the query to the connected database:

$ usql sqlserver://sa:pass@localhost
Connected with driver sqlserver (Microsoft SQL Server 2025 17.0.5005.3, RTM-CU9, Enterprise Developer Edition (64-bit))
Type "help" for help.

ms:sa@localhost/master=# select * from authors;
 author_id |     name
-----------+--------------
         1 | Isaac Asimov
         2 | Stephen King
(2 rows)

ms:sa@localhost/master=# select title from books
ms:sa@localhost/master-# where author_id = 2
ms:sa@localhost/master-# \p
select title from books
where author_id = 2
ms:sa@localhost/master-# \g
 title
--------
 Carrie
 Cujo
(2 rows)

ms:sa@localhost/master=#

A command takes one or more parameters. A parameter can be quoted with either ' or ", and can also be backticked.

How input becomes statements

usql reads input as psql does, on every database:

  • A statement ends at a ; that is outside a string, a quoted name and a comment, or at a meta command such as \g.
  • Write \; for a ; that must not end the statement. usql sends it as ;.
  • The body of a stored program between BEGIN and END, and on Oracle an anonymous block, stays in one statement, so its ; need no escape. Inside a PL/SQL package, or in the declarations of a unit before its BEGIN, write each ; as \;.
  • A line with only / and SQL Server's GO are not separators. They are text of the statement, as in psql.
  • Input that is not typed, from -c, -f, a pipe or \i, runs a last statement that has no ;.
  • \if, \elif, \else and \endif choose the lines that run, as in psql. A branch that does not run sends no statement, runs no other meta command and replaces no variable, and the prompt's %R shows @ there.
Line editing

The interactive interpreter edits lines with rline, which reads ~/.inputrc (or the file that INPUTRC names) as GNU Readline does. For example, set editing-mode vi turns on vi mode, and "\e[A": history-search-backward makes Up search the history for entries that start with what is typed. Settings inside $if usql ... $endif apply only to usql.

Backslash Commands

usql supports interleaved backslash (\) meta commands to modify or alter the way that usql interprets queries, formats its output, and changes the resulting interactive flow.

(not connected)=> \c postgres://user:pass@localhost
pg:user@localhost=> select * from my_table \G

Available backslash meta commands can be displayed with \?:

$ usql
Type "help" for help.

(not connected)=> \?
General
  \q                                quit usql
  \copyright                        show usage and distribution terms for usql
  \errverbose                       show most recent error message at maximum verbosity
  \drivers                          show database drivers available to usql

Help
  \?                                show help on usql's meta (backslash) commands
  \? commands                       as \?, but shows all command aliases
  \? options                        show help on usql command-line options
  \? variables                      show help on special usql variables
  \? styles                         show usql syntax highlighting styles

Connection
  \c DSN or \c NAME                 connect to dsn or named database connection
  \c DRIVER PARAMS...               connect to database with driver and parameters
  \conninfo [-password]             display information about the current database connection,
                                    with the password when -password is given
  \Z                                close (disconnect) database connection
  \password [USER]                  change password for user

Query Execute
  \g [(OPTIONS)] [FILE] or ;        execute query (and send results to file or |pipe)
  \G [(OPTIONS)] [FILE]             as \g, but forces vertical output mode
  \gx [(OPTIONS)] [FILE]            as \g, but forces expanded output mode
  \gexec                            execute query and execute each value of the result
  \gset [PREFIX]                    execute query and store results in usql variables
  \gdesc                            describe result of query, without executing it
  \bind [PARAM]...                  set query parameters
  \timing [on|off]                  toggle timing of commands

Query View
  \crosstab [(OPTIONS)] [COLUMNS]   execute query and display results in crosstab
  \chart CHART [(OPTIONS)]          execute query and display results as a chart
  \watch [(OPTIONS)] [INTERVAL]     execute query every specified interval

Query Buffer
  \e [-raw] [FILE] [LINE]           edit the query buffer (or file) with external editor (-raw
                                    for the non-interpolated buffer)
  \ef [FUNCNAME [LINE]]             edit function definition with external editor
  \ev [VIEWNAME [LINE]]             edit view definition with external editor
  \p [-raw]                         show the contents of the query buffer (-raw for the
                                    non-interpolated buffer)
  \raw                              as \p, but forces raw mode
  \w [-raw] FILE                    write the query buffer to file (-raw for the
                                    non-interpolated buffer)
  \r                                reset (clear) the query buffer
  \s [FILE]                         display history or save it to file
  \hist [COUNT]                     show the history, or its last COUNT entries

Informational
  (options: S = show system objects, x = expanded mode, + = additional detail)
  \d[Sx+] [NAME]                    list tables, views, and sequences or describe table, view,
                                    sequence, or index
  \da[Sx+] [PATTERN]                list aggregates
  \dA[x+] [PATTERN]                 list access methods
  \dAc[x+] [AMPTRN [TYPEPTRN]]      list operator classes
  \dAf[x+] [AMPTRN [TYPEPTRN]]      list operator families
  \dAo[x+] [AMPTRN [PATTERN]]       list operators of operator families
  \dAp[x+] [AMPTRN [PATTERN]]       list support functions of operator families
  \db[x+] [PATTERN]                 list tablespaces
  \dc[Sx+] [PATTERN]                list conversions
  \dconfig[x+] [PATTERN]            list configuration parameters
  \dC[x+] [PATTERN]                 list casts
  \dd[Sx] [PATTERN]                 show object descriptions not displayed elsewhere
  \dD[Sx+] [PATTERN]                list domains
  \ddp[x] [PATTERN]                 list default privileges
  \dE[Sx+] [PATTERN]                list foreign tables
  \des[x+] [PATTERN]                list foreign servers
  \det[x+] [PATTERN]                list foreign tables and their servers
  \deu[x+] [PATTERN]                list user mappings
  \dew[x+] [PATTERN]                list foreign-data wrappers
  \df[anptw][Sx+] [NAME [TYPES]]    list [only agg/normal/procedure/trigger/window] functions
  \dF[x+] [PATTERN]                 list text search configurations
  \dFd[x+] [PATTERN]                list text search dictionaries
  \dFp[x+] [PATTERN]                list text search parsers
  \dFt[x+] [PATTERN]                list text search templates
  \dg[Sx+] [PATTERN]                list roles
  \di[Sx+] [PATTERN]                list indexes
  \dl[x+]                           list large objects, same as \lo_list
  \dL[Sx+] [PATTERN]                list procedural languages
  \dm[Sx+] [PATTERN]                list materialized views
  \dn[Sx+] [PATTERN]                list schemas
  \do[Sx+] [NAME [TYPES]]           list operators
  \dO[Sx+] [PATTERN]                list collations
  \dp[Sx] [PATTERN]                 list table, view, and sequence access privileges
  \dP[itn][x+] [PATTERN]            list [only index/table] partitioned relations [n=nested]
  \drds[x] [ROLEPTRN [DBPTRN]]      list per-database role settings
  \drg[Sx] [PATTERN]                list role grants
  \dRp[x+] [PATTERN]                list replication publications
  \dRs[x+] [PATTERN]                list replication subscriptions
  \ds[Sx+] [PATTERN]                list sequences
  \dt[Sx+] [PATTERN]                list tables
  \dT[Sx+] [PATTERN]                list data types
  \du[Sx+] [PATTERN]                list roles
  \dv[Sx+] [PATTERN]                list views
  \dx[x+] [PATTERN]                 list extensions
  \dX[x] [PATTERN]                  list extended statistics
  \dy[x+] [PATTERN]                 list event triggers
  \l[x+] [PATTERN]                  list databases
  \z[Sx] [PATTERN]                  same as \dp
  \sf[+] FUNCNAME                   show a function's definition
  \sv[+] VIEWNAME                   show a view's definition
  \ss[+] TABLE [k]                  show stats for the columns of a table
  \k[+] [OPTIONS] [SCOPE]           list databases in Kubernetes, with the URL for \c (OPTIONS:
                                    -A, -n NAMESPACE, --context NAME)

Settings
  \config [OPTIONS] [NAME [VALUE]]  set configuration option NAME (SECTION.NAME), or show the
                                    settings of usql and print if no parameters (OPTIONS: -all
                                    shows every section, -password shows passwords)
  \pset [NAME [VALUE]]              set table print formatting option, or show all print
                                    formatting options if no parameters
  \uset [NAME [VALUE]]              set usql configuration option, or show all usql settings if
                                    no parameters
  \cset [NAME [URL]]                set named connection, or show all named connections if no
                                    parameters
  \cset NAME DRIVER PARAMS...       set named connection for driver and parameters

Input/Output
  \echo [-n] [MESSAGE]...           write message to standard output (-n for no newline)
  \qecho [-n] [MESSAGE]...          write message to \o output stream (-n for no newline)
  \warn [-n] [MESSAGE]...           write message to standard error (-n for no newline)
  \o [FILE]                         send all query results to file or |pipe
  \copy SRC DST QUERY TABLE         copy results of query from source database into table on
                                    destination database
  \copy SRC DST QUERY TABLE(A,...)  copy results of query from source database into table's
                                    columns on destination database
  \dump [OPTIONS] [FILE]            write the database as a usql script, or its schema as json
                                    or yaml, to the output, a file or |pipe (OPTIONS: -format
                                    FORMAT, -target DRIVER, -schema-only, -data-only, -schema
                                    PATTERN, -exclude-schema PATTERN, -table PATTERN,
                                    -exclude-table PATTERN, -allow-lossy, -allow-text,
                                    -restrict-key KEY)

Control/Conditional
  \set [NAME [VALUE]]               set script variable, or show all script variables if no
                                    parameters
  \unset NAME                       unset (delete) script variable
  \prompt [-TYPE] VAR [PROMPT]      prompt user to set script variable
  \i FILE                           execute commands from file
  \ir FILE                          as \i, but relative to location of current script
  \if EXPR                          begin conditional block
  \elif EXPR                        alternative within current conditional block
  \else                             final alternative within current conditional block
  \endif                            end conditional block
  \restrict RESTRICT_KEY            enter restricted mode with provided key
  \unrestrict RESTRICT_KEY          exit restricted mode if key matches

Transaction
  \begin [-read-only [ISOLATION]]   begin transaction, with optional isolation level
  \commit                           commit current transaction
  \rollback                         rollback (abort) current transaction

Operating System/Environment
  \! [COMMAND]                      execute command in shell or start interactive shell
  \cd [DIR]                         change the current working directory
  \getenv VARNAME ENVVAR            fetch environment variable
  \setenv NAME [VALUE]              set or unset environment variable of the commands that usql
                                    runs
(not connected)=>

Parameters passed to commands can be backticked.

Features and Compatibility

An overview of usql's features, functionality, and compatibility with psql:

The usql project's goal is to support as much of psql's core features and functionality, and aims to be as compatible as possible - contributions are always appreciated!

Configuration

Every setting of usql has a name with a section in front of it, as in print.border. The sections are:

SectionWhat it holdsCommand
usqlthe settings of usql, such as the pager and the prompts\uset
printthe display formatting settings\pset
varsthe script variables\set
chartsthe settings of \chart: charts.path names the directory of charts\config
envvariables of the environment of the commands that usql runs\setenv
connectionsthe named connections\cset
aliasesmeta commands of the user, set only in config.yaml

The \config meta command shows and sets any setting by its full name. Each command in the table sets only its own section. On the command line, --option NAME=VALUE, or -O NAME=VALUE, sets a setting by its full name. -v, -U, -N and -P set the sections vars, usql, connections and print.

(not connected)=> \config print.border 2
Border style is 2.
(not connected)=> \config print.border
print.border 2
(not connected)=> \config vars
vars.FOO                 'bar'
vars.LAST_ERROR_MESSAGE  ''
vars.LAST_ERROR_SQLSTATE '00000'
vars.VERSION             'usql 0.0.0-dev on linux/amd64, compiled by go1.27.4'
vars.VERSION_NAME        '0.0.0-dev'
vars.VERSION_NUM         '0'
(not connected)=>

\config with no arguments shows the sections usql and print. \config -all shows every section, and \config SECTION shows one section. The password of a connection URL shows as xxxxx, unless -password is given. Nothing that \config sets is saved.

The config.yaml File

usql reads its settings from a YAML file, config.yaml, when it starts. It reads the first of these:

  1. The file that --config names.
  2. The file that the USQL_CONFIG environment variable names.
  3. usql/config.yaml, or usql/config.yml, in the configuration directory of the system: %AppData%\usql\config.yaml on Windows, $HOME/Library/Application Support/usql/config.yaml on macOS, and $XDG_CONFIG_HOME/usql/config.yaml on Linux and other Unix systems, which is $HOME/.config/usql/config.yaml when XDG_CONFIG_HOME is not set. macOS does not read XDG_CONFIG_HOME. Set USQL_CONFIG to use another file there.

Each section of the file is a map of names and values:

usql:
  pager: less -S
  on_error_stop: on
print:
  border: 2
  null: (null)
vars:
  SCHEMA: public
charts:
  path: charts
env:
  PGAPPNAME: usql
connections:
  my_couchbase_conn: couchbase://Administrator:P4ssw0rd@localhost
  my_oracle_conn:
    protocol: oracle
    username: system
    password: P4ssw0rd
    hostname: localhost
    port: 1521
    database: free
aliases:
  tables: '\dt+'

A value keeps the text that it is written with, so on stays on and 0123 keeps its zero. Loading the file prints nothing. A setting that usql cannot set is an error that names the file, the line and the setting, and usql goes on with the other settings. A key at the top of the file that is not a section is an error that names the section where it belongs.

The settings apply in this order, and a later one wins over an earlier one:

  1. The defaults of usql, which read PAGER, EDITOR, VISUAL, SSLMODE and NO_COLOR, and TERM_GRAPHICS at a terminal.
  2. config.yaml.
  3. The USQL_PAGER, USQL_EDITOR, USQL_SSLMODE, USQL_SHOW_HOST_INFORMATION and USQL_TERM_GRAPHICS environment variables.
  4. The command line, in the order of its options.
  5. init.sql.
  6. The commands of the session.
connections:

Named connection DSNs are defined under connections: as a URL, as a list of a driver and its parameters, or as a map of the parts of a URL, as above. A named connection can be used on the command-line, and with \connect, \c, \copy, and other commands:

$ usql my_oracle_conn
Connected with driver oracle (Oracle Database 23.0.0.0.0)
Type "help" for help.

or:system@localhost/free=>
Password Commands

A password command is a command that writes the password of a connection, such as a command of a password manager. usql runs it when it opens a connection whose URL has no password. Put password_command in the map of a named connection, or set usql.password_command for every connection:

usql:
  password_command: pass show databases/default
connections:
  ora-prod:
    protocol: oracle
    username: system
    hostname: ora-prod.example.com
    port: 1521
    database: free
    password_command: op read op://Databases/ora-prod/password

The command of a named connection wins over usql.password_command. usql runs the command through the shell, as it runs \!. The command reads the parts of the URL on its standard input, with one KEY=VALUE line for each part, as git gives them to its credential helpers:

protocol=oracle
host=ora-prod.example.com
port=1521
database=free
username=system

protocol is the full name of the driver. A key with no value is left out. When the URL has no user name, username is the user of the system.

The first line of the standard output of the command is the password. The standard error of the command goes to the standard error of usql. When the command exits with a status other than 0, or writes nothing, usql connects with no password, and -W asks for one. When the command runs for more than 10 seconds, usql stops it, writes an error that names the command, and connects with no password. usql does not show the password, and does not put it in a variable.

\connect, \copy and -W run the command. usql runs no command for a URL that has a password, for a database file such as a SQLite file, for a named connection of a driver and its parameters, or for a connection that dbfwd forwards.

env:

The settings of env are added to the environment of each command that usql runs: a shell command of \!, a backtick, \g |command, \o |command, the pager and the editor. They do not change the environment of usql itself, so env.USQL_PAGER does not set the pager. \setenv NAME VALUE sets env.NAME, and \setenv NAME removes NAME from the environment of the commands.

aliases:

An alias is a meta command of the user. With the alias tables: '\dt+', the input \tables runs \dt+. The text of an alias can be meta commands, SQL, or several lines, and runs as the text of -c does. An alias cannot take the name of a meta command of usql. Only config.yaml sets an alias. \? commands lists the aliases after the meta commands.

The words after the name of an alias are its arguments. usql reads them as it reads the arguments of \set. Quotes are removed, a variable is replaced by its value, and a command between backticks runs. While the alias runs, the first word is the variable arg1, the second is arg2, and so on. The text uses them as other variables, as :arg1, :'arg1' and :"arg1":

aliases:
  rows: 'select count(*) from :"arg1";'

With this alias, \rows books runs select count(*) from "books";. A word that is not given leaves its variable unset, so :arg2 stays as it is written, as in psql. An alias with no words also runs, and then no argN variable is set. An alias that runs another alias gives it its own words.

When the alias ends, each argN variable gets back the value that it had before the alias, and a variable that was not set is unset again. A statement that the alias leaves in the query buffer stays there. Its variables are replaced when it is sent, after arg1 and the others have their old values again. To use a word in a statement, end the statement with ; in the text of the alias.

Variables

usql has script variables, connection variables, display formatting variables, and settings of its own. They are set with \set, \cset, \pset and \uset respectively, or with \config by their full names, such as vars.FOO and print.border. \set is only for scripts: a setting such as pager is not a variable, and \set pager less is an error that says to use \uset.

Runtime Variables

Script variables are managed with the \set and \unset commands:

(not connected)=> \unset FOO
(not connected)=> \set FOO bar
(not connected)=>

Script variables can be displayed with \set:

(not connected)=> \set
FOO = 'bar'
LAST_ERROR_MESSAGE = ''
LAST_ERROR_SQLSTATE = '00000'
VERSION = 'usql 0.0.0-dev on linux/amd64, compiled by go1.27.4'
VERSION_NAME = '0.0.0-dev'
VERSION_NUM = '0'
(not connected)=>
Variable Interpolation

When a script variable NAME has been \set, then :NAME, :'NAME', and :"NAME" will be interpolated into the query buffer:

ms:sa@localhost/master=# \set FOO 'Stephen King'
ms:sa@localhost/master=# select * from authors where name = :'FOO';
 author_id |     name
-----------+--------------
         2 | Stephen King
(1 row)

ms:sa@localhost/master=#

Where a runtime variable is used as :'NAME' or :"NAME", the interpolated value is quoted as a string literal or as a quoted name, as the database of the connection reads it. On SQL Server, :'NAME' gives N'...' and :"NAME" gives [...]. On MySQL, :"NAME" gives a name between backticks. On PostgreSQL, a value with a backslash gives E'...', as in psql. When usql is not connected, the value is quoted with ' or ", and each ' or " in it is doubled. When a value cannot be quoted for the database, usql reports an error and leaves the variable as it is written:

ms:sa@localhost/master=# \set TBLNAME authors
ms:sa@localhost/master=# \set COLNAME name
ms:sa@localhost/master=# \set FOO 'Isaac Asimov'
ms:sa@localhost/master=# select * from :TBLNAME where :"COLNAME" = :'FOO'
ms:sa@localhost/master-#

The query buffer and interpolated values can be displayed with \p and \print, or the raw query buffer can be displayed with \raw:

ms:sa@localhost/master=# select * from :TBLNAME where :"COLNAME" = :'FOO'
ms:sa@localhost/master-# \p
select * from authors where [name] = N'Isaac Asimov'
ms:sa@localhost/master-# \raw
select * from :TBLNAME where :"COLNAME" = :'FOO'
ms:sa@localhost/master-#

Note

Variables contained within other strings will not be interpolated:

ms:sa@localhost/master=# select ':FOO' as foo;
 foo
------
 :FOO
(1 row)

ms:sa@localhost/master=# \p
select ':FOO' as foo;
ms:sa@localhost/master=#

Connection Variables

Connection variables work similarly to runtime variables, and are managed with \cset. Connection variables can be used with the \c, \connect, \copy, or other commands:

(not connected)=> \cset my_conn sqlserver://sa:pass@localhost
(not connected)=> \c my_conn
Connected with driver sqlserver (Microsoft SQL Server 2025 17.0.5005.3, RTM-CU9, Enterprise Developer Edition (64-bit))
ms:sa@localhost/master=#

Connection variables are not interpolated into queries. See the configuration section for information on defining persistent connection variables.

Connection variables can be displayed with \cset:

(not connected)=> \cset
my_conn 'postgres://user:xxxxx@localhost'
(not connected)=>
Display Formatting (Print) Variables

Display formatting variables can be set using \pset and other commands:

(not connected)=> \pset time Kitchen
Time display is "Kitchen" ("3:04PM").
(not connected)=> \a
Output format is unaligned.
(not connected)=>

Display formatting variables can be displayed with \pset:

(not connected)=> \pset
border                   1
columns                  0
csv_fieldsep             ","
expanded                 off
fieldsep                 "|"
fieldsep_zero            off
footer                   on
format                   aligned
header_align             center
json_indent              0
linestyle                ascii
locale                   C
null                     ""
numericlocale            off
pager                    off
pager_min_lines          0
recordsep                "\n"
recordsep_zero           off
tableattr
time                     Kitchen
timezone
title
tuples_only              off
unicode_border_linestyle single
unicode_column_linestyle single
unicode_header_linestyle single
xheader_width            full
(not connected)=>
Settings

The settings of usql, such as the pager, the editor, the prompts and on_error_stop, are managed with the \uset command, which works as \pset does. Without arguments it shows every setting, with a name it shows that setting, and with a name and a value it sets it. The value is read as the other meta commands read an argument: it can be quoted, :name is interpolated and a backtick runs a command.

(not connected)=> \uset pager "less -R"
pager is "less -R"
(not connected)=> \uset on_error_stop on
on_error_stop is on
(not connected)=> \uset
echo                  none
echo_hidden           off
editor                ""
encoding              utf-8
fetch_count           0
on_error_stop         on
pager                 "less -R"
password_command      ""
prompt1               "%S%N%m%/%R%# "
prompt2               "%S%N%m%/%R%# "
prompt3               ">> "
quiet                 off
show_host_information true
sslmode               retry
syntax_hl             true
syntax_hl_format      terminal256
syntax_hl_override_bg true
syntax_hl_style       onedark
term_graphics
(not connected)=>

A setting can also be given on the command line with --uset NAME=VALUE, or -U NAME=VALUE, or -O usql.NAME=VALUE, and -q is --uset quiet=on. The environment variables PAGER, EDITOR and VISUAL give the default value of their settings, which config.yaml can change. The environment variables USQL_PAGER, USQL_EDITOR, USQL_SSLMODE, USQL_SHOW_HOST_INFORMATION and USQL_TERM_GRAPHICS win over config.yaml.

A script read with -f, \i, \ir, init.sql or from a pipe is UTF-8 unless it starts with the byte order mark of UTF-16 or UTF-32, as a file that Windows Notepad or PowerShell saved can. For a script in another encoding, set encoding to its name in the WHATWG Encoding Standard, such as windows-1252, shift_jis, euc-kr or gb18030:

$ usql --uset encoding=windows-1252 -f legacy.sql pg://

A file takes the setting when it is opened, and a pipe when it is first read. A script that is not valid UTF-8 in its encoding stops usql with an error that names the file and the line.

Use the \? variables command to display help information and to list the variables and the settings recognized by usql:

(not connected)=> \? variables
Backticks

Backslash (\) meta commands support backticks on parameters:

(not connected)=> \echo Welcome `echo $USER` -- 'running on:' "(" `uname -s` ")"
Welcome user -- running on: ( Linux )
(not connected)=>

usql passes a backticked parameter, exactly as written, to the shell that USQL_SHELL or else SHELL names. A backticked parameter can be combined with \set:

(not connected)=> \set MYVAR `uname -s`
(not connected)=> \set
LAST_ERROR_MESSAGE = ''
LAST_ERROR_SQLSTATE = '00000'
MYVAR = 'Linux'
SHELL_ERROR = 'false'
SHELL_EXIT_CODE = '0'
VERSION = 'usql 0.0.0-dev on linux/amd64, compiled by go1.27.4'
VERSION_NAME = '0.0.0-dev'
VERSION_NUM = '0'
(not connected)=> \echo :MYVAR
Linux
(not connected)=>
Copying Between Databases

usql provides a \copy command that reads data from a source database DSN and writes to a destination database DSN:

(not connected)=> \cset PGDSN postgres://user:pass@localhost
(not connected)=> \cset MYDSN mysql://user:pass@localhost
(not connected)=> \copy PGDSN MYDSN 'select book_id, author_id from books' 'books(id, author_id)'

As demonstrated above, the \copy command does not require being connected to a database, and will not modify or change the current open database connection or state.

Any valid URL or DSN name can be used for the source and destination database:

(not connected)=> \cset MYDSN mysql://user:pass@localhost
(not connected)=> \copy postgres://user:pass@localhost MYDSN 'select book_id, author_id from books' 'books(id, author_id)'

usql writes the rows to the destination in batches, and each batch commits alone. If a copy fails, the rows of the batches before the error stay in the table. The destination must be a database whose tables dbmeta can read and fill, and \copy refuses any other database with an error that names it.


Note

usql's \copy is distinct from and does not function like psql's \copy.


Copy Parameters

The \copy command has two parameter forms:

\copy SRC DST QUERY TABLE
\copy SRC DST QUERY TABLE(COL1, COL2, ..., COLN)

Where:

  • SRC - is the source database URL to connect to, and where the QUERY will be executed
  • DST - is the destination database URL to connect to, and where the destination TABLE resides
  • QUERY - is the query to execute on the SRC connection, the results of which will be copied to TABLE
  • TABLE - is the destination table name, followed by an optional SQL-like column list of the form (COL1, COL2, ..., COLN)
  • (COL1, COL2, ..., COLN) - a list of the destination column names, 1-to-N

The usual rules for variables, interpolation, and quoting apply to \copy's parameters.

Quoting

QUERY and TABLE must be quoted when containing spaces:

$ usql
(not connected)=> \echo :SOURCE_DSN :DESTINATION_DSN
pg://postgres:P4ssw0rd@localhost/ mysql://localhost
(not connected)=> \copy :SOURCE_DSN :DESTINATION_DSN 'select * from mySourceTable' 'myDestination(colA, colB)'
COPY 2
Column Counts

The QUERY must return the same number of columns as defined by the TABLE expression:

$ usql
(not connected)=> \copy csvq:. sq:test.db 'select * from authors' authors
error: the query gives 2 columns, and the copy into authors fills 1: name
(not connected)=> \copy csvq:. sq:test.db 'select name from authors' authors(name)
COPY 2
Datatype Compatibility and Casting

usql finds TABLE as the destination database finds it, and reads its columns from the catalog of the destination. It converts each value to the type of its column, such as the text 1 to an integer. It reads each value by the rules of the driver of the source, so a MySQL TIMESTAMP keeps its instant in any time zone of the client, and a SQL Server UNIQUEIDENTIFIER keeps the order of its bytes. A value that the column cannot hold stops the copy with an error that names the column and the row.

If a QUERY returns a value that usql cannot convert, the QUERY can use the conversion functions of the source database to cast the column to a type that TABLE's column takes:

$ usql
(not connected)=> \copy postgres://user:pass@localhost mysql://user:pass@localhost 'SELECT uuid_column::TEXT FROM myPgTable' myMyTable
COPY 1
Importing Data from CSV

The \copy command is capable of importing data from CSV's (or any other database!) using the csvq driver:

$ cat authors.csv
author_id,name
1,Isaac Asimov
2,Stephen King
$ cat books.csv
book_id,author_id,title
1,1,I Robot
2,2,Carrie
3,2,Cujo
$ usql
Type "help" for help.

(not connected)=> -- setting variables to make connections easier
(not connected)=> \set SOURCE_DSN csvq://.
(not connected)=> \set DESTINATION_DSN sqlite3:booktest.db
(not connected)=> -- connecting to the destination and creating the schema
(not connected)=> \c :DESTINATION_DSN
Connected with driver sqlite3 (SQLite 3.54.1)
sq:booktest.db=> create table authors (author_id integer, name text);
CREATE TABLE
sq:booktest.db=> create table books (book_id integer not null primary key autoincrement, author_id integer, title text);
CREATE TABLE
sq:booktest.db=> -- adding an extra row to books prior to copying
sq:booktest.db=> insert into books (author_id, title) values (1, 'Foundation');
INSERT 1
sq:booktest.db=> -- disconnecting to demonstrate that \copy opens new database connections
sq:booktest.db=> \disconnect
(not connected)=> -- copying data from SOURCE -> DESTINATION
(not connected)=> \copy :SOURCE_DSN :DESTINATION_DSN 'select * from authors' authors
COPY 2
(not connected)=> \copy :SOURCE_DSN :DESTINATION_DSN 'select author_id, title from books' 'books(author_id, title)'
COPY 3
(not connected)=> \c :DESTINATION_DSN
Connected with driver sqlite3 (SQLite 3.54.1)
sq:booktest.db=> select * from authors;
 author_id |     name
-----------+--------------
         1 | Isaac Asimov
         2 | Stephen King
(2 rows)

sq:booktest.db=> select * from books;
 book_id | author_id |   title
---------+-----------+------------
       1 |         1 | Foundation
       2 |         1 | I Robot
       3 |         2 | Carrie
       4 |         2 | Cujo
(4 rows)

sq:booktest.db=>

Note

When importing large datasets (> 1GiB) from one database to another, it is better to use a database's native clients and tools.


Reusing Connections with Copy

The \copy command (and all usql commands) works with variables. When scripting, or when needing to perform multiple \copy operations from/to multiple sources/destinations, the best practice is to \set connection variables either in a script or in the init.sql startup script.

Similarly, passwords can be kept out of scripts by defining named connections in the config.yaml file.

For example:

$ cat $HOME/.config/usql/config.yaml
connections:
  pglocal: postgres://postgres:P4ssw0rd@localhost:49153?sslmode=disable
  orlocal: oracle://system:P4ssw0rd@localhost:1521/orasid
$ usql
Type "help" for help.

(not connected)=> \copy pglocal orlocal 'select staff_id, first_name from staff' 'staff(staff_id, first_name)'
COPY 18
Dumping a Database

usql writes a database as a usql script, which usql -f runs to make the database again. The script holds the schema and the rows, in the order that pg_dump writes them. --target writes it for another database, such as DuckDB.

--format json and --format yaml write the schema with no rows, as dbmeta reads it. This is dbmeta's snapshot of the schema. It lists the tables, columns, indexes, views and other objects in a fixed order, so the same database gives the same file. A diff of two files shows how two schemas differ. The YAML file has the keys of the JSON file, in the same order. The default format is sql, the script.

On the command line, --dump, or -D, writes the dump to standard output, or to the file that -o names, and then exits. Inside usql, \dump writes it to the output, to a file, or to a command after |:

$ usql pg://localhost/app --dump -o app.sql
$ usql pg://localhost/app --dump --target duckdb --exclude-table 'audit%'
$ usql pg://localhost/app --dump --format json -o app.json
(not connected)=> \c pg://localhost/app
pg:user@localhost/app=> \dump -schema-only schema.sql
pg:user@localhost/app=> \dump -table 'app.%' |gzip > app.sql.gz
pg:user@localhost/app=> \dump -format yaml app.yaml

--dump and \dump take the same options. The command line writes them as --NAME, and \dump as -NAME:

OptionWhat it does
format FORMATsql, the default, or json or yaml for the schema with no rows
target DRIVERwrite the dump for another database, such as duckdb
schema-onlydump the schema and no rows
data-onlydump the rows and no schema
schema PATTERNdump the schemas that match the pattern, which can repeat
exclude-schema PATTERNdo not dump the schemas that match the pattern, which can repeat
table PATTERNdump the tables that match the pattern, which can repeat
exclude-table PATTERNdo not dump the tables that match the pattern, which can repeat
allow-lossyallow a type of the target that holds less than the source type
allow-textallow the string type of the target for a type that it does not have
restrict-key KEYthe key of the \restrict line of the dump, random by default

A pattern is a pattern of SQL LIKE. A table pattern with a dot, such as app.%, matches the schema and the table together.

The formats json and yaml take the patterns and schema-only. They refuse data-only, target, allow-lossy, allow-text and restrict-key, because the snapshot holds no rows, is not written for a target and is not a script.

The dump reads the schema and the rows in one transaction, so that they agree. Inside a transaction that \begin started, \dump reads in that transaction, and so it includes the changes that are not committed yet. Outside such a transaction, the dump goes to a temporary file that only its owner can read, and its destination gets the dump only when it is complete. So standard output or a command gets a whole script or nothing. When the database fails to read the rows, the dump waits and starts again in a new transaction, at most 3 times. A value that the dump cannot write stops it at once. Oracle refuses to read a table that was made a few seconds before the transaction started, and a new try a little later reads it. A file is written whole or not at all, and only its owner can read it. --dump runs no init.sql. Neither form reads its options from config.yaml, -O or a USQL_ variable, so that a setting cannot change what a dump writes.

Syntax Highlighting

Interactive input is highlighted as you type it. usql parses the input with the grammar of transit, and the SQL of each statement with the grammar of the dialect of the connection. The colors come from a style of transit, which has the styles of Chroma. The settings that control highlighting are:

SettingDefaultValuesDescription
syntax_hltruetrue or falseturns highlighting on and off
syntax_hl_formatdependent on terminal supportnoop, terminal, terminal256, terminal16mthe number of colors: none, 16, 256 or 24 bits
syntax_hl_override_bgtruetrue or falsekeeps the background of the terminal, and not the style's
syntax_hl_styleonedarkstyle namethe name of a style

They are set with \uset. \? styles lists the names of the styles, and names the style in use. A terminal with no color, or a NO_COLOR variable, turns highlighting off by default:

$ usql
Type "help" for help.

(not connected)=> \uset syntax_hl_style dracula
syntax_hl_style is dracula
(not connected)=> \uset syntax_hl off
syntax_hl is false
(not connected)=>
Context Completion

When using the interactive shell, context completion is available in usql by hitting the <Tab> key. For example, hitting <Tab> can complete some parts of SELECT queries on a SQL Server database:

$ usql sqlserver://sa:pass@localhost
Connected with driver sqlserver (Microsoft SQL Server 2025 17.0.5005.3, RTM-CU9, Enterprise Developer Edition (64-bit))
Type "help" for help.

ms:sa@localhost/master=# select * f
 1 from
 2 fetch
 3 full outer join

Or, for example completing backslash commands while connected to a database:

$ usql sqlserver://sa:pass@localhost
Connected with driver sqlserver (Microsoft SQL Server 2025 17.0.5005.3, RTM-CU9, Enterprise Developer Edition (64-bit))
Type "help" for help.

ms:sa@localhost/master=# \g
 1 \g        4 \gset     7 \getenv
 2 \go       5 \gdesc
 3 \gx       6 \gexec

Not all commands, contexts, or databases support completion. To help improve it, see the section below on contributing.

Command completion can be canceled with <Control-C>.

Time Formatting

By default, usql prints a date, a time and a timestamp as psql prints them, on every database that it knows the time types of:

TypeDisplay
date2026-10-10
time12:34:56.5
time with time zone12:34:56+05:30
timestamp2026-10-10 12:34:56.5
timestamp with time zone2026-10-10 12:34:56+07

A fraction of a second has no zeros at its end. An offset has its minutes only when they are not zero. A timestamp with a time zone prints in the zone that \pset timezone sets. When it is not set, a timestamp of PostgreSQL prints in the time zone of the session, as psql prints it, and SET TIME ZONE changes that zone. On another database, it prints in the zone that the driver gives it. A value of a column whose type usql does not know prints in RFC3339Nano.

\pset time FORMAT prints every time/date column with one Go time format instead. \pset time '' goes back to the default:

$ usql sqlserver://sa:pass@localhost
Connected with driver sqlserver (Microsoft SQL Server 2025 17.0.5005.3, RTM-CU9, Enterprise Developer Edition (64-bit))
Type "help" for help.

ms:sa@localhost/master=# \pset time
Time display is unset. Each date and time prints as psql prints its type.
ms:sa@localhost/master=# select cast('2026-10-31 09:41:27.123456' as datetime2) as stamp;
           stamp
----------------------------
 2026-10-31 09:41:27.123456
(1 row)

ms:sa@localhost/master=# \pset time Kitchen
Time display is "Kitchen" ("3:04PM").
ms:sa@localhost/master=# select cast('2026-10-31 09:41:27.123456' as datetime2) as stamp;
 stamp
--------
 9:41AM
(1 row)

ms:sa@localhost/master=#

usql's time format supports any Go supported time format, or can be any standard Go const name, such as Kitchen above. See below for an overview of the available time constants.

Time Constants

The following are the time constant names available in usql, corresponding time format value, and example display output:

ConstantFormatDisplay ↓
ANSICMon Jan _2 15:04:05 2006Wed Aug 3 20:12:48 2022
UnixDateMon Jan _2 15:04:05 MST 2006Wed Aug 3 20:12:48 UTC 2022
RubyDateMon Jan 02 15:04:05 -0700 2006Wed Aug 03 20:12:48 +0000 2022
RFC82202 Jan 06 15:04 MST03 Aug 22 20:12 UTC
RFC822Z02 Jan 06 15:04 -070003 Aug 22 20:12 +0000
RFC850Monday, 02-Jan-06 15:04:05 MSTWednesday, 03-Aug-22 20:12:48 UTC
RFC1123Mon, 02 Jan 2006 15:04:05 MSTWed, 03 Aug 2022 20:12:48 UTC
RFC1123ZMon, 02 Jan 2006 15:04:05 -0700Wed, 03 Aug 2022 20:12:48 +0000
RFC33392006-01-02T15:04:05Z07:002022-08-03T20:12:48Z
RFC3339Nano2006-01-02T15:04:05.999999999Z07:002022-08-03T20:12:48.693257Z
Kitchen3:04PM8:12PM
StampJan _2 15:04:05Aug 3 20:12:48
StampMilliJan _2 15:04:05.000Aug 3 20:12:48.693
StampMicroJan _2 15:04:05.000000Aug 3 20:12:48.693257
StampNanoJan _2 15:04:05.000000000Aug 3 20:12:48.693257000

↓ Generated using timestamp 2022-08-03T20:12:48.693257Z

Host Connection Information

By default, usql displays connection information when it connects to a database. Some databases and connections do not work with this. Set the environment variable USQL_SHOW_HOST_INFORMATION to false to turn it off:

$ export USQL_SHOW_HOST_INFORMATION=false
$ usql sqlserver://sa:pass@localhost
Type "help" for help.

ms:sa@localhost/master=#

show_host_information is a setting of usql, and is set with \uset. Additionally, it can be passed via the command-line using --uset:

$ usql --uset show_host_information=false sqlserver://sa:pass@localhost
Type "help" for help.

ms:sa@localhost/master=# \uset show_host_information true
show_host_information is true
ms:sa@localhost/master=# \connect sqlserver://sa:pass@localhost
Connected with driver sqlserver (Microsoft SQL Server 2025 17.0.5005.3, RTM-CU9, Enterprise Developer Edition (64-bit))
ms:sa@localhost/master=#
Terminal Graphics

usql supports terminal graphics for Kitty, iTerm, and Sixel enabled terminals using the github.com/kenshaw/rasterm package. Terminal graphics are on only in an interactive session, unless the command line turns them on, as described below.

Detection and Support

When it starts at a terminal, usql asks the terminal which graphics it draws, and waits up to 250 ms for the answer. In tmux, it asks tmux for the terminal of its client. When the terminal does not answer, usql reads TERM, TERM_PROGRAM and the other environment variables of the terminal. USQL_TERM_GRAPHICS and TERM_GRAPHICS choose the graphics with no query. Keys typed while usql waits for the answer go to the line editor.

When support is available, the logo will be displayed at the start of an interactive session:

Charts and Graphs

The \chart command can be used to display a chart directly in the terminal:

\chart help lists the charts and their options. \chart file=NAME writes the chart to a file as SVG, and does not need a terminal with graphics. See _samples/chart.sql for a sample that makes a PostgreSQL table and draws it.

The renderer is zuzu, which draws charts in pure Go, so a build with CGO_ENABLED=0 has the renderer too. The text of a chart uses the IBM Plex Sans font that zuzu holds, so a chart looks the same on every machine. Every build has it, unless its build tags leave it out. The tag no_charts leaves it out, and so does no_drivers unless the tag charts is also given. A build without it reports that it has no chart renderer.

Charts from a Vega-Lite File

\chart spec=NAME draws a Vega-Lite spec that you write, with the rows of the query as its data. usql reads the file NAME, NAME.json or NAME.vl.json, in that order, in the directory of the setting charts.path. That directory is charts in the directory of the configuration file, unless the setting names another.

usql sets the data of the spec to the rows, with one object for each row and the column names as the keys. A column of numbers gives numbers, and a NULL in it gives null. Every other column gives strings, and a NULL in it gives an empty string. size and bg apply only when the spec has no width, height or background. title, subtitle and type cannot be used with spec. file and the terminal graphics work as for any chart.

For example, put this spec in charts/bars.json:

{
  "mark": "bar",
  "encoding": {
    "x": {"field": "fruit", "type": "nominal"},
    "y": {"field": "sold", "type": "quantitative"}
  }
}

Then this query writes a bar chart to out.svg:

select 'Apples' as fruit, 28 as sold union all select 'Figs', 81
\chart spec=bars file=out.svg

zuzu draws the marks bar, line, area, point, circle, square, tick, rect, rule, text, arc and trail, and the composite marks boxplot, errorbar and errorband. It leaves out a feature of the spec that it does not support, and usql does not report it.

Enabling/Disabling Terminal Graphics

Terminal graphics can be forced enabled or disabled by setting the USQL_TERM_GRAPHICS or the TERM_GRAPHICS environment variable:

# disable
$ USQL_TERM_GRAPHICS=none usql

# force iterm graphics
$ TERM_GRAPHICS=iterm usql
NameDefaultValues
USQL_TERM_GRAPHICS, TERM_GRAPHICSfound out at a terminal, and none otherwiseempty, kitty, iterm, sixel, none
the setting usql.term_graphicsthe value of the variablesthe same

USQL_TERM_GRAPHICS wins over TERM_GRAPHICS. An empty value finds out what the terminal draws. Outside a terminal, only the command line can turn the graphics on, as in -O usql.term_graphics=kitty.

Terminals with Graphics Support

The following terminals have been tested with usql:

  • WezTerm is a cross-platform terminal for Windows, macOS, Linux, and many other platforms that supports iTerm graphics

  • iTerm2 is a macOS terminal that supports iTerm graphics

  • kitty is a terminal for Linux, macOS, and various BSDs that supports Kitty graphics

  • foot is a Wayland terminal for Linux (and other Wayland hosts) that supports Sixel graphics

Additional terminals that support Sixel graphics are catalogued on the Are We Sixel Yet? website.

Startup Script

usql runs the file init.sql in its configuration directory at startup, as psql runs ~/.psqlrc. It runs after usql opens the connection named on the command line, and before any -c / --command or -f / --file flag and before the first prompt:

  1. $XDG_CONFIG_HOME/usql/init.sql on Linux and other Unix systems, which is $HOME/.config/usql/init.sql when XDG_CONFIG_HOME is not set.
  2. $HOME/Library/Application Support/usql/init.sql on macOS.
  3. %AppData%\usql\init.sql on Windows.

The USQLRC environment variable names another file. usql reads the file as it reads a file passed with -f / --file, so it can hold any meta command and any SQL statement. A statement runs on the connection named on the command line, and fails with error: not connected when there is none. usql writes the error of a failed statement and goes on, unless on_error_stop is on. The file is commonly used to set variables and settings:

$ cat $HOME/.config/usql/init.sql
\echo WELCOME TO THE JUNGLE `date`
\uset syntax_hl_style paraiso-dark

-- set a color prompt (the default prompt is "%S%N%m%/%R%# ")
\uset prompt1 "\033[32m%S%m%/%R%#\033[0m"
$ usql
WELCOME TO THE JUNGLE Thu Jun 14 02:36:53 WIB 2018
Type "help" for help.

(not connected)=> \uset syntax_hl_style
syntax_hl_style is "paraiso-dark"
(not connected)=>

See _samples/init.sql for a sample.

Pass -X or --no-init on the command-line to skip the file:

$ usql --no-init pg://

usql no longer reads $HOME/.usqlrc, the init: script of config.yaml or the $HOME/.usqlpass password file. Move the script to init.sql, and define named connections in the config.yaml file in place of the password file.

History

At a terminal, usql keeps the history of what was typed in the file history in its state directory:

  1. $XDG_STATE_HOME/usql/history on Linux and other Unix systems, which is $HOME/.local/state/usql/history when XDG_STATE_HOME is not set.
  2. $HOME/Library/Application Support/usql/history on macOS.
  3. %LocalAppData%\usql\history on Windows.

The USQL_HISTORY environment variable names another file. usql prints a warning at startup when it cannot read the file, and then does not save the history. It does not read $HOME/.usql_history.

Additional Notes

The following are additional notes and miscellania related to usql:

Release Builds

Release builds include every driver, and are built with additional SQLite3 build tags (see: build.sh). The 32 bit arm build leaves out ChaiSQL and DuckDB.

macOS

The recommended installation method on macOS is via brew due to the way library dependencies for the sqlite3 driver are done on macOS. If the following (or similar) error is encountered when attempting to run usql:

$ usql
dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicuuc.68.dylib
  Referenced from: /Users/user/.local/bin/usql
  Reason: image not found
Abort trap: 6

Then missing library dependency can be fixed by installing icu4c using brew:

$ brew install icu4c
Running `brew update --auto-update`...
==> Downloading ...
...

$ usql
(not connected)=>

ODBC FAQ

Why does the SQLite ODBC driver crash on Linux?

On Linux, the first query through the SQLite ODBC driver crashes usql in a build that links both the sqlite3 driver and DuckDB, as a build with every driver does. The DuckDB bindings export the sqlite3_* functions of the SQLite that the sqlite3 driver carries. The SQLite ODBC driver then gets some of its sqlite3_* functions from usql and some from the system SQLite, and the two copies do not match. The odbc project explains it in full.

If you need the SQLite ODBC driver, build with the tag libsqlite3. The sqlite3 driver then uses the SQLite of the system, and exports no sqlite3_* function. Add the tag to a build with every driver, or build with only the ODBC driver:

# every driver, with the SQLite of the system
$ go install -tags libsqlite3 github.com/xo/usql@main

# only the ODBC driver
$ go install -tags 'no_drivers odbc libsqlite3' github.com/xo/usql@main

The other ODBC drivers work without the tag. The PostgreSQL Unicode driver was checked against PostgreSQL 18.

Couchbase FAQ

Why does a transaction fail to commit with error 17007?

The server could not meet the durability that the transaction asked for. By default a transaction asks for majority, which a single-node server cannot meet. usql does not change the durability unless you ask it to. Set durability_level=none in the URL for a single-node server, such as a local development server:

$ usql "couchbase://user:pass@localhost/?durability_level=none"

The other values are majority, majorityAndPersistActive and persistToMajority.

Why does a transaction stay open longer than the server's default?

The server ends a transaction after 15 seconds by default, which is too short for a person typing into one. usql sets txtimeout=30m when the URL does not set txtimeout. Set it in the URL to choose another value:

$ usql "couchbase://user:pass@localhost/?txtimeout=2m"

Contributing

usql is currently a WIP, and is aiming towards a 1.0 release soon. Report a bug, ask a question, or propose a feature in GitHub Discussions. The repository takes no issues and no pull requests. For technical details, see CONTRIBUTING.md.