Use the Built-in SQL Client

CockroachDB comes with a built-in client for executing SQL statements from an interactive shell or directly from the command line. To use this client, run the cockroach sql command as described below.

To exit the interactive shell, use \q, quit, exit, or ctrl-d.

Tip:

If you want to experiment with CockroachDB SQL but do not have a cluster already running, you can use the cockroach demo command to open a shell to a temporary, in-memory cluster.

Synopsis

  1. # Start the interactive SQL shell:
  2. $ cockroach sql <flags>
  3. # Execute SQL from the command line:
  4. $ cockroach sql --execute="<sql statement>;<sql statement>" --execute="<sql-statement>" <flags>
  5. $ echo "<sql statement>;<sql statement>" | cockroach sql <flags>
  6. $ cockroach sql <flags> < file-containing-statements.sql
  7. # Exit the interactive SQL shell:
  8. $ \q
  9. $ quit
  10. $ exit
  11. ctrl-d
  12. # View help:
  13. $ cockroach sql --help

Flags

The sql command supports the following types of flags:

General

  • To start an interactive SQL shell, run cockroach sql with all appropriate connection flags or use just the —url flag, which includes connection details.
  • To execute SQL statements from the command line, use the —execute flag.
    FlagDescription
    —database-dA database name to use as current database in the newly created session.
    —echo-sqlReveal the SQL statements sent implicitly by the command-line utility. For a demonstration, see the example below.This can also be enabled within the interactive SQL shell via the \set echo shell command.
    —execute-eExecute SQL statements directly from the command line, without opening a shell. This flag can be set multiple times, and each instance can contain one or more statements separated by semi-colons. If an error occurs in any statement, the command exits with a non-zero status code and further statements are not executed. The results of each statement are printed to the standard output (see —format for formatting options).For a demonstration of this and other ways to execute SQL from the command line, see the example below.
    —formatHow to display table rows printed to the standard output. Possible values: tsv, csv, table, raw, records, sql, html.Default: table for sessions that output on a terminal; tsv otherwiseThis flag corresponds to the display_format client-side option.
    —safe-updatesDisallow potentially unsafe SQL statements, including DELETE without a WHERE clause, UPDATE without a WHERE clause, and ALTER TABLE … DROP COLUMN.Default: true for interactive sessions; false otherwisePotentially unsafe SQL statements can also be allowed/disallowed for an entire session via the sql_safe_updates session variable.
    —setSet a client-side option before starting the SQL shell or executing SQL statements from the command line via —execute. This flag may be specified multiple times, once per option.After starting the SQL shell, the \set and unset commands can be use to enable and disable client-side options as well.

Client connection

FlagDescription
—hostThe server host and port number to connect to. This can be the address of any node in the cluster. Env Variable: COCKROACH_HOSTDefault: localhost:26257
—port-pThe server port to connect to. Note: The port number can also be specified via —host. Env Variable: COCKROACH_PORTDefault: 26257
—user-uThe SQL user that will own the client session.Env Variable: COCKROACH_USERDefault: root
—insecureUse an insecure connection.Env Variable: COCKROACH_INSECUREDefault: false
—certs-dirThe path to the certificate directory containing the CA and client certificates and client key.Env Variable: COCKROACH_CERTS_DIRDefault: ${HOME}/.cockroach-certs/
—urlA connection URL to use instead of the other arguments.Env Variable: COCKROACH_URLDefault: no URL

See Client Connection Parameters for more details.

Logging

By default, the sql command logs errors to stderr.

If you need to troubleshoot this command's behavior, you can change its logging behavior.

Session and output types

cockroach sql exhibits different behaviors depending on whether or not the session is interactive and/or whether or not the session outputs on a terminal.

  • A session is interactive when cockroach sql is invoked without the —execute flag and input is not redirected from a file. In such cases:
    • The errexit option defaults to false.
    • The check_syntax option defaults to true if supported by the CockroachDB server (this is checked when the shell starts up).
    • Ctrl+C at the prompt will only terminate the shell if no other input was entered on the same line already.
    • The shell will attempt to set the safe_updates session variable to true on the server.
  • A session outputs on a terminal when output is not redirected to a file. In such cases:
    • The —format flag and its corresponding display_format option default to table. These default to tsv otherwise.
    • The show_times option defaults to true.
      When a session is both interactive and outputs on a terminal, cockroach sql also activates the interactive prompt with a line editor that can be used to modify the current line of input. Also, command history becomes active.

SQL shell

Welcome message

When the SQL shell connects (or reconnects) to a CockroachDB node, it prints a welcome text with some tips and CockroachDB version and cluster details:

  1. # Welcome to the cockroach SQL interface.
  2. # All statements must be terminated by a semicolon.
  3. # To exit: CTRL + D.
  4. #
  5. # Server version: CCL v19.1.0 (darwin amd64, built 2017/07/13 11:43:06, go1.10.1) (same version as client)
  6. # Cluster ID: 7fb9f5b4-a801-4851-92e9-c0db292d03f1
  7. #
  8. # Enter \? for a brief introduction.
  9. #
  10. >

The Version and Cluster ID details are particularly noteworthy:

  • When the client and server versions of CockroachDB are the same, the shell prints the Server version followed by (same version as client).
  • When the client and server versions are different, the shell prints both the Client version and Server version. In this case, you may want to plan an upgrade of older client or server versions.
  • Since every CockroachDB cluster has a unique ID, you can use the Cluster ID field to verify that your client is always connecting to the correct cluster.

Commands

The following commands can be used within the interactive SQL shell:

CommandUsage
\qquitexitctrl-dExit the shell.When no text follows the prompt, ctrl-c exits the shell as well; otherwise, ctrl-c clears the line.
!Run an external command and print its results to stdout. See the example below.
|Run the output of an external command as SQL statements. See the example below.
\set <option>\unset <option>Enable or disable a client-side option. For more details, see Client-side options.As of v2.1, you can also use the —set flag to enable or disable client-side options before starting the SQL shell.
\?helpView this help within the shell.
\h <statement>\hf <function>View help for specific SQL statements or functions. See SQL shell help for more details.

Client-side options

  • To view option descriptions and how they are currently set, use \set without any options.
  • To enable or disable an option, use \set <option> <value> or \unset <option> <value>. As of v2.1, you can also use the form <option>=<value>.
  • If an option accepts a boolean value:
    • \set <option> without <value> is equivalent to \set <option> true, and \unset <option> without <value> is equivalent to \set <option> false.
    • As of v2.1, on and 0 are aliases for true, and off and 1 are aliases for false.
      Client OptionsDescription
      auto_traceFor every statement executed, the shell also produces the trace for that statement in a separate result below. A trace is also produced in case the statement produces a SQL error.Default: offTo enable this option, run \set auto_trace on.
      display_formatHow to display table rows printed within the interactive SQL shell. Possible values: tsv, csv, table, raw, records, sql, html.Default: table for sessions that output on a terminal; tsv otherwiseTo change this option, run \set display_format <format>. For a demonstration, see the example below.
      echoReveal the SQL statements sent implicitly by the SQL shell.Default: falseTo enable this option, run \set echo. For a demonstration, see the example below.
      errexitExit the SQL shell upon encountering an error.Default: false for interactive sessions; true otherwiseTo enable this option, run \set errexit.
      check_syntaxValidate SQL syntax. This ensures that a typo or mistake during user entry does not inconveniently abort an ongoing transaction previously started from the interactive shell.Default: true for interactive sessions; false otherwise.To disable this option, run \unset check_syntax.
      show_timesReveal the time a query takes to complete.Default: trueTo disable this option, run \unset show_times.
      smart_promptQuery the server for the current transaction status and return it to the prompt. Note that this option is respected only when ECHO is enabled as well.Default: true for interactive sessions; false otherwiseTo disable this option, run \unset smart_prompt.

Help

Within the SQL shell, you can get interactive help about statements and functions:

CommandUsage
\h??List all available SQL statements, by category.
\hfList all available SQL functions, in alphabetical order.
\h <statement>or <statement> ?View help for a specific SQL statement.
\hf <function>or <function> ?View help for a specific SQL function.

Examples

  1. > \h UPDATE
  1. Command: UPDATE
  2. Description: update rows of a table
  3. Category: data manipulation
  4. Syntax:
  5. UPDATE <tablename> [[AS] <name>] SET ... [WHERE <expr>] [RETURNING <exprs...>]
  6. See also:
  7. SHOW TABLES
  8. INSERT
  9. UPSERT
  10. DELETE
  11. https://www.cockroachlabs.com/docs/v2.1/update.html
  1. > \hf uuid_v4
  1. Function: uuid_v4
  2. Category: built-in functions
  3. Returns a UUID.
  4. Signature Category
  5. uuid_v4() -> bytes [ID Generation]
  6. See also:
  7. https://www.cockroachlabs.com/docs/v2.1/functions-and-operators.html

Shortcuts

The SQL shell supports many shortcuts, such as ctrl-r for searching the shell history. For full details, see this Readline Shortcut reference.

Examples

Start a SQL shell

In these examples, we connect a SQL shell to a secure cluster.

  1. # Using standard connection flags:
  2. $ cockroach sql \
  3. --certs-dir=certs \
  4. --user=maxroach \
  5. --host=12.345.67.89 \
  6. --database=critterdb
  1. # Using the --url flag:
  2. $ cockroach sql \
  3. --url="postgresql://maxroach@12.345.67.89:26257/critterdb?sslcert=certs/client.maxroach.crt&sslkey=certs/client.maxroach.key&sslmode=verify-full&sslrootcert=certs/ca.crt"

In these examples, we connect a SQL shell to an insecure cluster.

  1. # Using standard connection flags:
  2. $ cockroach sql --insecure \
  3. --user=maxroach \
  4. --host=12.345.67.89 \
  5. --database=critterdb
  1. # Using the --url flag:
  2. $ cockroach sql \
  3. --url="postgresql://maxroach@12.345.67.89:26257/critterdb?sslmode=disable"

Execute SQL statement within the SQL shell

This example assume that we have already started the SQL shell (see examples above).

  1. > CREATE TABLE animals (id INT PRIMARY KEY DEFAULT unique_rowid(), name STRING);
  1. > INSERT INTO animals (name) VALUES ('bobcat'), ('? '), ('barn owl');
  1. > SELECT * FROM animals;
  1. +--------------------+----------+
  2. | id | name |
  3. +--------------------+----------+
  4. | 148899952591994881 | bobcat |
  5. | 148899952592060417 | ? |
  6. | 148899952592093185 | barn owl |
  7. +--------------------+----------+

Execute SQL statements from the command line

In these examples, we use the —execute flag to execute statements from the command line:

  1. # Statements with a single --execute flag:
  2. $ cockroach sql --insecure \
  3. --execute="CREATE TABLE roaches (name STRING, country STRING); INSERT INTO roaches VALUES ('American Cockroach', 'United States'), ('Brownbanded Cockroach', 'United States')" \
  4. --user=maxroach \
  5. --host=12.345.67.89 \
  6. --database=critterdb
  1. CREATE TABLE
  2. INSERT 2
  1. # Statements with multiple --execute flags:
  2. $ cockroach sql --insecure \
  3. --execute="CREATE TABLE roaches (name STRING, country STRING)" \
  4. --execute="INSERT INTO roaches VALUES ('American Cockroach', 'United States'), ('Brownbanded Cockroach', 'United States')" \
  5. --user=maxroach \
  6. --host=12.345.67.89 \
  7. --database=critterdb
  1. CREATE TABLE
  2. INSERT 2

In this example, we use the echo command to execute statements from the command line:

  1. # Statements with the echo command:
  2. $ echo "SHOW TABLES; SELECT * FROM roaches;" | cockroach sql --insecure --user=maxroach --host=12.345.67.89 --database=critterdb
  1. +----------+
  2. | Table |
  3. +----------+
  4. | roaches |
  5. +----------+
  6. +-----------------------+---------------+
  7. | name | country |
  8. +-----------------------+---------------+
  9. | American Cockroach | United States |
  10. | Brownbanded Cockroach | United States |
  11. +-----------------------+---------------+

Control how table rows are printed

In these examples, we show tables and special characters printed in various formats.

When the standard output is a terminal, —format defaults to table and tables are printed with ASCII art and special characters are not escaped for easy human consumption:

  1. $ cockroach sql --insecure \
  2. --execute="SELECT '?' AS chick, '?' AS turtle" \
  3. --user=maxroach \
  4. --host=12.345.67.89 \
  5. --database=critterdb
  1. +-------+--------+
  2. | chick | turtle |
  3. +-------+--------+
  4. | ? | ? |
  5. +-------+--------+

However, you can explicitly set —format to another format, for example, tsv or html:

  1. $ cockroach sql --insecure \
  2. --format=tsv \
  3. --execute="SELECT '?' AS chick, '?' AS turtle" \
  4. --user=maxroach \
  5. --host=12.345.67.89 \
  6. --database=critterdb
  1. 1 row
  2. chick turtle
  3. ? ?
  1. $ cockroach sql --insecure \
  2. --format=html \
  3. --execute="SELECT '?' AS chick, '?' AS turtle" \
  4. --user=maxroach \
  5. --host=12.345.67.89 \
  6. --database=critterdb
  1. <table>
  2. <thead><tr><th>chick</th><th>turtle</th></tr></head>
  3. <tbody>
  4. <tr><td>?</td><td>?</td></tr>
  5. </tbody>
  6. </table>

When piping output to another command or a file, —format defaults to tsv:

  1. $ cockroach sql --insecure \
  2. --execute="SELECT '?' AS chick, '?' AS turtle" > out.txt \
  3. --user=maxroach \
  4. --host=12.345.67.89 \
  5. --database=critterdb
  1. $ cat out.txt
  1. 1 row
  2. chick turtle
  3. ? ?

However, you can explicitly set —format to another format, for example, table:

  1. $ cockroach sql --insecure \
  2. --format=table \
  3. --execute="SELECT '?' AS chick, '?' AS turtle" > out.txt \
  4. --user=maxroach \
  5. --host=12.345.67.89 \
  6. --database=critterdb
  1. $ cat out.txt
  1. +-------+--------+
  2. | chick | turtle |
  3. +-------+--------+
  4. | ? | ? |
  5. +-------+--------+
  6. (1 row)

Make the output of SHOW statements selectable

To make it possible to select from the output of SHOW statements, set —format to raw:

  1. $ cockroach sql --insecure \
  2. --format=raw \
  3. --user=maxroach \
  4. --host=12.345.67.89 \
  5. --database=critterdb
  1. > SHOW CREATE customers;
  1. # 2 columns
  2. # row 1
  3. ## 14
  4. test.customers
  5. ## 185
  6. CREATE TABLE customers (
  7. id INT NOT NULL,
  8. email STRING NULL,
  9. CONSTRAINT "primary" PRIMARY KEY (id ASC),
  10. UNIQUE INDEX customers_email_key (email ASC),
  11. FAMILY "primary" (id, email)
  12. )
  13. # 1 row

When —format is not set to raw, you can use the display_format SQL shell option to change the output format within the interactive session:

  1. > \set display_format raw
  1. # 2 columns
  2. # row 1
  3. ## 14
  4. test.customers
  5. ## 185
  6. CREATE TABLE customers (
  7. id INT NOT NULL,
  8. email STRING NULL,
  9. CONSTRAINT "primary" PRIMARY KEY (id ASC),
  10. UNIQUE INDEX customers_email_key (email ASC),
  11. FAMILY "primary" (id, email)
  12. )
  13. # 1 row

Execute SQL statements from a file

In this example, we show and then execute the contents of a file containing SQL statements.

  1. $ cat statements.sql
  1. CREATE TABLE roaches (name STRING, country STRING);
  2. INSERT INTO roaches VALUES ('American Cockroach', 'United States'), ('Brownbanded Cockroach', 'United States');
  1. $ cockroach sql --insecure \
  2. --user=maxroach \
  3. --host=12.345.67.89 \
  4. --database=critterdb \
  5. < statements.sql
  1. CREATE TABLE
  2. INSERT 2

Run external commands from the SQL shell

In this example, we use ! to look at the rows in a CSV file before creating a table and then using | to insert those rows into the table.

Note:
This example works only if the values in the CSV file are numbers. For values in other formats, use an online CSV-to-SQL converter or make your own import program.

  1. > \! cat test.csv
  1. 12, 13, 14
  2. 10, 20, 30
  1. > CREATE TABLE csv (x INT, y INT, z INT);
  1. > \| IFS=","; while read a b c; do echo "insert into csv values ($a, $b, $c);"; done < test.csv;
  1. > SELECT * FROM csv;
  1. +----+----+----+
  2. | x | y | z |
  3. +----+----+----+
  4. | 12 | 13 | 14 |
  5. | 10 | 20 | 30 |
  6. +----+----+----+

In this example, we create a table and then use | to programmatically insert values.

  1. > CREATE TABLE for_loop (x INT);
  1. > \| for ((i=0;i<10;++i)); do echo "INSERT INTO for_loop VALUES ($i);"; done
  1. > SELECT * FROM for_loop;
  1. +---+
  2. | x |
  3. +---+
  4. | 0 |
  5. | 1 |
  6. | 2 |
  7. | 3 |
  8. | 4 |
  9. | 5 |
  10. | 6 |
  11. | 7 |
  12. | 8 |
  13. | 9 |
  14. +---+

Edit SQL statements in an external editor

In applications that use GNU Readline (such as bash), you can edit a long line in your preferred editor by typing Ctrl-x Ctrl-e. However, CockroachDB uses the BSD-licensed libedit, which does not include this functionality.

If you would like to be able to edit the current line in an external editor by typing C-x C-e as in bash, do the following:

  • Install the vipe program (from the moreutils suite of tools).
  • Edit your ~/.editrc to add the following line, which takes advantage of the SQL client's ability to run external commands:
  1. cockroach:bind -s ^X^E '^A^K\\\| echo \"^Y\" | vipe\r'

This tells libedit to translate C-x C-e into the following commands:

  • Move to the beginning of the current line.
  • Cut the whole line.
  • Paste the line into your editor via vipe.
  • Pass the edited file back to the SQL client when vipe exits.

Note:

Future versions of the SQL client may opt to use a different back-end for reading input, in which case please refer to this page for additional updates.

Allow potentially unsafe SQL statements

The —safe-updates flag defaults to true. This prevents SQL statements that may have broad, undesired side-effects. For example, by default, we cannot use DELETE without a WHERE clause to delete all rows from a table:

  1. $ cockroach sql --insecure --execute="SELECT * FROM db1.t1"
  1. +----+------+
  2. | id | name |
  3. +----+------+
  4. | 1 | a |
  5. | 2 | b |
  6. | 3 | c |
  7. | 4 | d |
  8. | 5 | e |
  9. | 6 | f |
  10. | 7 | g |
  11. | 8 | h |
  12. | 9 | i |
  13. | 10 | j |
  14. +----+------+
  15. (10 rows)
  1. $ cockroach sql --insecure --execute="DELETE FROM db1.t1"
  1. Error: pq: rejected: DELETE without WHERE clause (sql_safe_updates = true)
  2. Failed running "sql"

However, to allow an "unsafe" statement, you can set —safe-updates=false:

  1. $ cockroach sql --insecure --safe-updates=false --execute="DELETE FROM db1.t1"
  1. DELETE 10

Note:
Potentially unsafe SQL statements can also be allowed/disallowed for an entire session via the sql_safe_updates session variable.

Reveal the SQL statements sent implicitly by the command-line utility

In this example, we use the —execute flag to execute statements from the command line and the —echo-sql flag to reveal SQL statements sent implicitly:

  1. $ cockroach sql --insecure \
  2. --execute="CREATE TABLE t1 (id INT PRIMARY KEY, name STRING)" \
  3. --execute="INSERT INTO t1 VALUES (1, 'a'), (2, 'b'), (3, 'c')" \
  4. --user=maxroach \
  5. --host=12.345.67.89 \
  6. --database=db1
  7. --echo-sql
  1. # Server version: CockroachDB CCL f8f3c9317 (darwin amd64, built 2017/09/13 15:05:35, go1.8) (same version as client)
  2. # Cluster ID: 847a4ba5-c78a-465a-b1a0-59fae3aab520
  3. > SET sql_safe_updates = TRUE
  4. > CREATE TABLE t1 (id INT PRIMARY KEY, name STRING)
  5. CREATE TABLE
  6. > INSERT INTO t1 VALUES (1, 'a'), (2, 'b'), (3, 'c')
  7. INSERT 3

In this example, we start the interactive SQL shell and enable the echo shell option to reveal SQL statements sent implicitly:

  1. $ cockroach sql --insecure \
  2. --user=maxroach \
  3. --host=12.345.67.89 \
  4. --database=db1
  1. > \set echo
  1. > INSERT INTO db1.t1 VALUES (4, 'd'), (5, 'e'), (6, 'f');
  1. > INSERT INTO db1.t1 VALUES (4, 'd'), (5, 'e'), (6, 'f');
  2. INSERT 3
  3. Time: 2.426534ms
  4. > SHOW TRANSACTION STATUS
  5. > SHOW DATABASE

See also

Was this page helpful?
YesNo