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][variables], [backticks][backticks],
[backslash commands][commands] and has additional features that psql does
not, such as multiple database support, [copying between databases][copying],
[context-based completion][completion],
and [terminal graphics][termgraphics].
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.

Installing
usql can be installed via Release, via Homebrew, via AUR, via
Go or via Docker:
Installing via Release
- Download a release for your platform
- Extract the
usql or usql.exe file from the .tar.bz2 or .zip file
- 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][xo-tap] in the usual way with the [brew
command][homebrew]:
# 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][aur-bin] in the usual way with the
[yay command][yay]:
# install usql
$ yay -S usql-bin
usql-bin installs the released binary. To build from source instead, use the
[usql][aur] package, which takes considerably longer because it compiles
every driver:
# build usql from source
$ yay -S usql
Alternately, build and [install using makepkg][arch-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][chart-command]:
# 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 chai driver
$ go install -tags chai 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][dburl].
The list of drivers that usql was built with can be displayed with the
[\drivers command][commands]:
$ 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][go-sql] that usql supports, the
associated database, scheme / build tag, and scheme aliases:
| Database |
Scheme / Tag |
Scheme Aliases |
Driver Package / Notes |
| PostgreSQL |
pgx |
postgres, pg, pgsql, postgresql, px |
github.com/jackc/pgx/v5/stdlib |
| MySQL |
mysql |
my, maria, aurora, mariadb, percona |
github.com/go-sql-driver/mysql |
| Microsoft SQL Server |
sqlserver |
ms, mssql, azuresql |
github.com/microsoft/go-mssqldb |
| Oracle Database |
oracle |
or, ora, oci, oci8, odpi, odpi-c |
github.com/xo/oracle |
| SQLite3 |
sqlite3 |
sq, sqlite, file |
github.com/mattn/go-sqlite3 † § |
| DuckDB |
duckdb |
dk, ddb, duck, file |
github.com/duckdb/duckdb-go/v2 † § |
|
|
|
|
| Alibaba MaxCompute |
maxcompute |
mc |
github.com/xo/dbimp/maxcompute ¶ |
| Alibaba Tablestore |
tablestore |
ot, ots |
github.com/xo/dbimp/tablestore ¶ |
| Amazon Athena |
athena |
s3, aws, awsathena |
github.com/xo/dbimp/athena ¶ |
| Amazon Redshift |
redshift |
rs |
github.com/jackc/pgx/v5/stdlib ¶ |
| Apache Avatica |
avatica |
av, phoenix |
github.com/xo/dbimp/avatica |
| Apache Drill |
drill |
dl |
github.com/xo/dbimp/drill |
| Apache Druid |
druid |
dr |
github.com/xo/dbimp/druid |
| Apache Hive |
hive |
hi, hive2 |
github.com/xo/dbimp/hive |
| Apache Impala |
impala |
im |
github.com/xo/dbimp/hive |
| Apache Pinot |
pinot |
pi |
github.com/xo/dbimp/pinot |
| Apache Solr |
solr |
so |
github.com/xo/dbimp/solr |
| ArangoDB |
arangodb |
ar, arango |
github.com/xo/dbimp/arangodb |
| Azure Cosmos DB |
cosmos |
cm |
github.com/xo/dbimp/cosmos ¶ |
| Cassandra |
cassandra |
ca, cql, scy, cass, scylla, datastax |
github.com/xo/cassandra |
| ChaiSQL |
chai |
ci, genji, chaisql |
github.com/chaisql/chai § ‡ |
| ClickHouse |
clickhouse |
ch |
github.com/xo/dbimp/clickhouse |
| CockroachDB |
cockroachdb |
cr, cdb, crdb, cockroach |
github.com/jackc/pgx/v5/stdlib |
| Couchbase |
couchbase |
n1, n1ql |
github.com/xo/dbimp/couchbase |
| CrateDB |
cratedb |
ct, crate |
github.com/jackc/pgx/v5/stdlib |
| CSVQ |
csvq |
cs, csv, tsv, json |
github.com/mithrandie/csvq-driver § |
| Databend |
databend |
dd, bend |
github.com/xo/dbimp/databend |
| Databricks |
databricks |
br, brick, bricks, databrick |
github.com/xo/dbimp/databricks ¶ |
| DynamoDB |
dynamodb |
dy, dyn, dynamo |
github.com/xo/dbimp/dynamodb |
| Elasticsearch |
elasticsearch |
es, elastic |
github.com/xo/dbimp/elasticsearch |
| Exasol |
exasol |
ex, exa |
github.com/xo/dbimp/exasol |
| Firebird |
firebird |
fb, firebirdsql |
github.com/nakagami/firebirdsql |
| FlightSQL |
flightsql |
fl, flight |
github.com/apache/arrow-go/v18/arrow/flight/flightsql/driver ‡ |
| Google BigQuery |
bigquery |
bq |
github.com/xo/dbimp/bigquery ¶ |
| Google Spanner |
spanner |
sp |
github.com/xo/dbimp/spanner ¶ |
| InfluxDB |
influxdb |
in, influx |
github.com/xo/dbimp/influxdb |
| InfluxDB InfluxQL |
influxql |
iq |
github.com/xo/dbimp/influxdb |
| libSQL |
libsql |
ls, turso |
github.com/xo/dbimp/libsql |
| ModernC SQLite3 |
moderncsqlite |
mq, modernsqlite |
modernc.org/sqlite § |
| Neo4j |
neo4j |
nj, neo, n4j |
github.com/xo/dbimp/neo4j |
| ODBC |
odbc |
od |
github.com/xo/odbc |
| OpenSearch |
opensearch |
os, open |
github.com/xo/dbimp/opensearch |
| PostgreSQL lib/pq |
libpq |
pq |
github.com/lib/pq |
| Presto |
presto |
pr, prestodb |
github.com/xo/dbimp/trino |
| QuestDB |
questdb |
qs |
github.com/jackc/pgx/v5/stdlib |
| rqlite |
rqlite |
rq |
github.com/xo/dbimp/rqlite |
| SAP HANA |
saphana |
sa, sap, hana, hdb |
github.com/SAP/go-hdb/driver ‡ |
| SingleStore MemSQL |
memsql |
me |
github.com/go-sql-driver/mysql |
| Snowflake |
snowflake |
sf |
github.com/xo/dbimp/snowflake ¶ |
| SurrealDB |
surrealdb |
sr, sur, surreal |
github.com/xo/dbimp/surrealdb |
| TiDB |
tidb |
ti |
github.com/go-sql-driver/mysql |
| Trino |
trino |
tr |
github.com/xo/dbimp/trino |
| Vertica |
vertica |
ve |
github.com/vertica/vertica-sql-go |
| Vitess Database |
vitess |
vt |
github.com/go-sql-driver/mysql |
| VoltDB |
voltdb |
vo, vdb, volt |
github.com/VoltDB/voltdb-client-go/voltdbclient |
| YDB |
ydb |
yd |
github.com/ydb-platform/ydb-go-sdk/v3 ‡ |
|
|
|
|
| NO DRIVERS |
no_drivers |
|
leave 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][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][connecting] 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][dburl] 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][commands].
Database connections can be defined with [the \cset command][connection-vars]
or in [the config.yaml configuration file][config].
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:
| Component |
Description |
driver |
driver scheme name or scheme alias |
transport |
tcp, udp, unix or driver name (for ODBC and ADODB) |
user |
username |
pass |
password |
host |
hostname |
dbname ± |
database name, instance, or service name/ID |
?opt1=a&... |
additional database driver options (see respective SQL driver for available options) |
/path/to/file |
a path on disk |
name |
a connection name set by [\cset][connection-vars] or in [config.yaml][config] |
± 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][dburl]. Databases have at least one or more aliases. See [dburl’s
scheme documentation][dburl-schemes] 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:[email protected]/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:[email protected]/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][connection-vars] for information on
defining connection names.
Executing Queries and Commands
The interactive interpreter reads queries and [backslash meta (\) commands][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][backticks].
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][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.
The section editor of [config.yaml][config] sets the line editor, with the
same keys as the shell [hail][hail]. Its keys win over ~/.inputrc:
| Key |
Default |
Description |
editor.vi |
false |
edits in vi mode |
editor.color |
true |
colors the input, and the text of \p, \sv and \sf |
editor.style |
onedark |
the style of the colors, as [Syntax Highlighting][highlighting] describes |
editor.styles |
|
the style of one kind of word, by the capture name of the grammar |
editor.bindings |
|
key bindings, as the lines of an inputrc file, read after the inputrc file of the user |
editor:
vi: true
bindings:
- '"\C-o": "\\x on\n"'
- 'set completion-ignore-case on'
editor.vi and editor.bindings are not usql.editor, which names the
external editor of \e.
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
提示:代码过长已自动截断
Parameters passed to commands [can be backticked][backticks].
Features and Compatibility
An overview of usql’s features, functionality, and compatibility with psql:
- [Configuration][config]
- [Variables][variables]
- [Backticks][backticks]
- [Copying Between Databases][copying]
- [Dumping a Database][dumping]
- [Syntax Highlighting][highlighting]
- [Time Formatting][timefmt]
- [Context Completion][completion]
- Host Connection Information
- [Startup Script][init]
- [History][history]
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][contributing]!
Configuration
Every setting of usql has a name with a section in front of it, as in
print.border. The sections are:
| Section |
What it holds |
Command |
usql |
the [settings][settings] of usql, such as the pager and the prompts |
\uset |
print |
the [display formatting settings][print-vars] |
\pset |
vars |
the [script variables][runtime-vars] |
\set |
charts |
the settings of \chart: charts.path names the directory of charts |
\config |
env |
variables of the environment of the commands that usql runs |
\setenv |
connections |
the [named connections][connection-vars] |
\cset |
history |
the [history][history] of the input |
\config |
editor |
the [line editor][line-editing], and the colors of the input |
\config |
aliases |
meta commands of the user, set only in config.yaml |
|
The \config [meta command][commands] 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][yaml] file,
config.yaml, when it starts. It reads the first of
these:
- The file that
--config names.
- The file that the
USQL_CONFIG environment variable names.
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
history:
size: 10000
control: [ignoreboth, erasedups]
editor:
style: dracula
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:
- The defaults of
usql, which read PAGER, EDITOR, VISUAL, SSLMODE
and NO_COLOR, and TERM_GRAPHICS at a terminal.
config.yaml.
- The
USQL_PAGER, USQL_EDITOR, USQL_SSLMODE,
USQL_SHOW_HOST_INFORMATION and USQL_TERM_GRAPHICS environment
variables.
- The command line, in the order of its options.
- [
init.sql][init].
- The commands of the session.
connections:
[Named connection DSNs][connecting] 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][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][runtime-vars] variables, [connection][connection-vars]
variables, [display formatting][print-vars] variables, and [settings][settings]
of its own. They are set with \set, \cset, \pset and \uset
respectively, or with [\config][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][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][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 in
README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论