> ## Documentation Index
> Fetch the complete documentation index at: https://cockroachlabs.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# cockroach sql

export const InternalLink = ({version, path = "", children, ...props}) => {
  let detectedVersion = version || "stable";
  if (typeof window !== 'undefined' && !version) {
    const match = window.location.pathname.match(/\/docs\/([^/]+)/);
    if (match) {
      detectedVersion = match[1];
    }
  }
  const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
  return <a href={`/docs/${detectedVersion}/${normalizedPath}`} {...props}>
      {children}
    </a>;
};

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` <InternalLink path="cockroach-commands">command</InternalLink> 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 <InternalLink path="cockroach-demo">`cockroach demo`</InternalLink> command to open a shell to a temporary, in-memory cluster.
</Tip>

The output of `cockroach sql` when used non-interactively is part of a stable interface, and can be used programmatically, with the exception of informational output lines that begin with the hash symbol (`#`). Informational output can change from release to release, and should not be used programmatically.

## Before you begin

* The <InternalLink path="create-role#role-options">role option of the user</InternalLink> logging in must be `LOGIN` or `SQLLOGIN`, which are granted by default. If the user has been set to use the `NOLOGIN` role or the `NOSQLLOGIN` <InternalLink path="security-reference/authorization#supported-privileges">system privilege</InternalLink> (or the legacy `NOSQLLOGIN` role), the user cannot log in using the SQL CLI with any authentication method.
* **macOS users only:** By default, macOS-based terminals do not enable handling of the Alt key modifier. This prevents access to many keyboard shortcuts in the unix shell and `cockroach sql`. See the section [macOS terminal configuration](#macos-terminal-configuration) below for details.

## Synopsis

Start the interactive SQL shell:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach sql <flags>
```

Execute SQL from the command line:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach sql --execute="<sql statement;<sql statement" --execute="<sql-statement" <flags>
```

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ echo "<sql statement;<sql statement" | cockroach sql <flags>
```

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach sql <flags> --file file-containing-statements.sql
```

Exit the interactive SQL shell:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> \q
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> quit
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> exit
```

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> Ctrl+D
```

View help:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach sql --help
```

## Flags

The `sql` command supports the following types of flags:

* [General Use](#general)
* [Client Connection](#client-connection)
* [Logging](#logging)

### General

* To start an interactive SQL shell, run `cockroach sql` with all appropriate connection flags or use just the [`--url` flag](#sql-flag-url), which includes <InternalLink path="connection-parameters#connect-using-a-url">connection details</InternalLink>.
* To execute SQL statements from the command line, use the [`--execute` flag](#sql-flag-execute).

<Note>
  | Flag                                                    | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
  | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  | `--database`<br /><br />`-d`                            | A database name to use as <InternalLink path="sql-name-resolution#current-database">current database</InternalLink> in the newly created session.                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
  | `--embedded`                                            | Minimizes the SQL shell [welcome text](#welcome-message) to be appropriate for embedding in playground-type environments. Specifically, this flag removes details that users in an embedded environment have no control over (e.g., networking information).                                                                                                                                                                                                                                                                                                                                                  |
  | `--echo-sql`                                            | Reveal the SQL statements sent implicitly by the command-line utility. For a demonstration, see the [example](#reveal-the-sql-statements-sent-implicitly-by-the-command-line-utility) below.<br /><br />This can also be enabled within the interactive SQL shell via the `\set echo` [shell command](#commands).                                                                                                                                                                                                                                                                                             |
  | <a id="sql-flag-execute" /> `--execute`<br /><br />`-e` | Execute 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).<br /><br />For a demonstration of this and other ways to execute SQL from the command line, see the [example](#execute-sql-statements-from-the-command-line) below. |
  | `--file <filename>`<br /><br />`-f <filename>`          | Read SQL statements from `<filename`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
  | <a id="sql-flag-format" /> `--format`                   | How to display table rows printed to the standard output. Possible values: `tsv`, `csv`, `table`, `raw`, `records`, `sql`, `html`.<br /><br />**Default:** `table` for sessions that [output on a terminal](#session-and-output-types); `tsv` otherwise<br /><br />This flag corresponds to the `display_format` [client-side option](#client-side-options).                                                                                                                                                                                                                                                  |
  | `--read-only`                                           | Sets the `default_transaction_read_only` <InternalLink path="show-vars#supported-variables">session variable</InternalLink> to `on` upon connecting.                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
  | <a id="flag-safe-updates" /> `--safe-updates`           | Disallow potentially unsafe SQL statements. For the complete list of disallowed statements, refer to the documentation for the <InternalLink path="set-vars">`sql_safe_updates` session variable</InternalLink>.<br /><br />**Default:** `true` for [interactive sessions](#session-and-output-types); `false` otherwise<br /><br />Potentially unsafe SQL statements can also be allowed/disallowed for an entire session via the <InternalLink path="set-vars">`sql_safe_updates` session variable</InternalLink>.                                                                                          |
  | `--set`                                                 | Set a [client-side option](#client-side-options) 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.<br /><br />After starting the SQL shell, the `\set` and `unset` commands can be use to enable and disable client-side options as well.                                                                                                                                                                                                                                                          |
  | `--watch`                                               | Repeat the SQL statements specified with `--execute` or `-e` until a SQL error occurs or the process is terminated. `--watch` applies to all `--execute` or `-e` flags in use.<br />You must also specify an interval at which to repeat the statement, followed by a time unit. For example, to specify an interval of 5 seconds, use `5s`.<br /><br /> Note that this flag is intended for simple monitoring scenarios during development and testing. See the [example](#repeat-a-sql-statement) below.                                                                                                    |
</Note>

### Client connection

| Flag                                                       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--url`                                                    | A <InternalLink path="connection-parameters#connect-using-a-url">connection URL</InternalLink> to use instead of the other arguments. To convert a connection URL to the syntax that works with your client driver, run <InternalLink path="connection-parameters#convert-a-url-for-different-drivers">`cockroach convert-url`</InternalLink>.<br /><br />**Env Variable:** `COCKROACH_URL`<br />**Default:** no URL                                                                                                                                                                                                                                                                                                                                                                                 |
| `--host`                                                   | The server host and port number to connect to. This can be the address of any node in the cluster. <br /><br />**Env Variable:** `COCKROACH_HOST`<br />**Default:** `localhost:26257`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `--port`<br /><br />`-p`                                   | The server port to connect to. Note: The port number can also be specified via `--host`. <br /><br />**Env Variable:** `COCKROACH_PORT`<br />**Default:** `26257`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `--user`<br /><br />`-u`                                   | The <InternalLink path="create-user">SQL user</InternalLink> that will own the client session.<br /><br />**Env Variable:** `COCKROACH_USER`<br />**Default:** `root`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `--insecure`                                               | Use an insecure connection.<br /><br />**Env Variable:** `COCKROACH_INSECURE`<br />**Default:** `false`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| <a id="flags-cert-principal-map" /> `--cert-principal-map` | A comma-separated list of `<cert-principal:<db-principal` mappings. This allows mapping the principal in a cert to a DB principal such as `node` or `root` or any SQL user. This is intended for use in situations where the certificate management system places restrictions on the `Subject.CommonName` or `SubjectAlternateName` fields in the certificate (e.g., disallowing a `CommonName` like `node` or `root`). If multiple mappings are provided for the same `<cert-principal`, the last one specified in the list takes precedence. A principal not specified in the map is passed through as-is via the identity function. A cert is allowed to authenticate a DB principal if the DB principal name is contained in the mapped `CommonName` or DNS-type `SubjectAlternateName` fields. |
| `--certs-dir`                                              | The path to the <InternalLink path="cockroach-cert">certificate directory</InternalLink> containing the CA and client certificates and client key.<br /><br />**Env Variable:** `COCKROACH_CERTS_DIR`<br />**Default:** `${HOME}/.cockroach-certs/`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |

See <InternalLink path="connection-parameters">Client Connection Parameters</InternalLink> for more details.

### Logging

By default, this command logs messages to `stderr`. This includes events with `WARNING` <InternalLink path="logging#logging-levels-severities">severity</InternalLink> and higher.

If you need to troubleshoot this command's behavior, you can <InternalLink path="configure-logs">customize its logging behavior</InternalLink>.

## 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 `-e` or `-f` flag, and the input is a terminal. In such cases:
  * The [`errexit` option](#sql-option-errexit) defaults to `false`.
  * The [`check_syntax` option](#sql-option-check-syntax) 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` <InternalLink path="set-vars">session variable</InternalLink> to `true` on the server.
  * The shell continues to read input after the last command entered.
* A session **outputs on a terminal** when output is not redirected to a file. In such cases:
  * The [`--format` flag](#sql-flag-format) and its corresponding [`display_format` option](#sql-option-display-format) 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:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
#
# Welcome to the CockroachDB SQL shell.
# All statements must be terminated by a semicolon.
# To exit, type: \q.
#
# Server version: CockroachDB CCL  (x86_64-apple-darwin17.7.0, built 2019/09/13 00:07:19, go1.12.6) (same version as client)
# Cluster ID: 7fb9f5b4-a801-4851-92e9-c0db292d03f1
#
# Enter \? for a brief introduction.
#
>
```

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 <InternalLink path="upgrade-cockroach-version">plan an upgrade</InternalLink> 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.

<Note>
  For clusters deployed in CockroachDB Cloud, do not use the cluster ID printed in the welcome message to verify the cluster your client is connected to. Instead, use the `ccloud cluster list` command to list the ID of each cluster in your CockroachDB Cloud organization to which you have access. To learn more about the `ccloud` command, refer to <InternalLink version="cockroachcloud" path="ccloud-get-started">Get Started with the `ccloud` CLI</InternalLink>.
</Note>

### Commands

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

| Command                                            | Usage                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `\?`,`help`                                        | View this help within the shell.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `\q`,`quit`,`exit`,`ctrl-d`                        | Exit the shell.<br />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`. <InternalLink path="cockroach-sql#run-external-commands-from-the-sql-shell">See an example</InternalLink>.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `\|`                                               | Run the output of an external command as SQL statements. <InternalLink path="cockroach-sql#run-external-commands-from-the-sql-shell">See an example</InternalLink>.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `\set <option>`,`\unset <option>`                  | Enable or disable a client-side option. For more details, see [Client-side options](#client-side-options).<br />You can also use the [`--set` flag](#general) to enable or disable client-side options before starting the SQL shell.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `\p`,`\show`                                       | During a multi-line statement or transaction, show the SQL that has been entered but not yet executed.<br />`\show` was deprecated as of v21.1. Use `\p` instead.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `\h <statement>`,`\hf <function>`                  | View help for specific SQL statements or functions. See [SQL shell help](#help) for more details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `\c <option>`,`\connect <option>`                  | Display or change the current <InternalLink path="connection-parameters">connection parameters</InternalLink>. Using `\c` without an argument lists the current connection parameters. <br />To reuse the existing connection and change the current database, use `\c <dbname>`. This is equivalent to `SET <database>` and `USE <database>`. <br />To connect to a cluster using individual connection parameters, use `\c <dbname> <user> <host> <port>`. Use the dash character (`-`) to omit one parameter. To reconnect to the cluster using the current connection parameters enter `\c -`. When using individual connection parameters, the TLS settings from the original connection are reused. To use different TLS settings, connect using a connection URL. <br />To connect to a cluster using a <InternalLink path="connection-parameters#connect-using-a-url">connection URL</InternalLink> use `\c <url>` |
| `\l`                                               | List all databases in the CockroachDB cluster. This command is equivalent to <InternalLink path="show-databases">`SHOW DATABASES`</InternalLink>.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `\d[S+] [<pattern]`                                | Show details about the relations in the current database. By default this command will show all the user tables, indexes, views, materialized views, and sequences in the current database. Add the `S` modifier to also show all system objects. If you specify a relation or a [pattern](#patterns), it will show the details of matching relations. Add the `+` modifier to show additional information.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `\dC[+] [<pattern]`                                | Show the type casts. If you specify a type or a [pattern](#patterns), it will show the details of matching types. Add the `+` modifier to show additional information.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `\dd[S] [<pattern]`                                | Show the objects of type `constraint` in the current database. Add the `S` modifier to also show all system objects. If you specify a type or a [pattern](#patterns), it will show the details of matching objects.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `\df[S+] [<pattern]`                               | Show the <InternalLink path="user-defined-functions">user-defined functions</InternalLink> of the current database. Add the `S` modifier to also show all <InternalLink path="functions-and-operators">system functions</InternalLink>. If you specify a function name or a [pattern](#patterns), it will show the details of matching function. Add the `+` modifier to show additional information.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `\dg[S+] [<pattern]`                               | Show the <InternalLink path="authorization">roles</InternalLink> of the current database. Add the `S` modifier to also show all system objects. If you specify a role name or a [pattern](#patterns), it will show the details of matching roles. Add the `+` modifier to show additional information.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `\di[S+] [<pattern]`                               | Show the indexes of the current database. Add the `S` modifier to also show all system objects. If you specify an index name or a [pattern](#patterns), it will show the details of matching indexes. Add the `+` modifier to show additional information.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `\dm[S+] [<pattern]`                               | Show the materialized views of the current database. Add the `S` modifier to also show all system objects. If you specify a materialized view name or a [pattern](#patterns), it will show the details of matching materialized views. Add the `+` modifier to show additional information.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `\dn[S+] [<pattern]`                               | List all <InternalLink path="sql-name-resolution#naming-hierarchy">schemas</InternalLink> in the current database. Add the `S` modifier to also show all system schemas. Add the `+` modifier to show the permissions of each schema. Specify a [pattern](#patterns) to limit the output to schemas that match the pattern. These commands are equivalent to <InternalLink path="show-schemas">`SHOW SCHEMAS`</InternalLink>.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `\ds[S+] [<pattern]`                               | Show the sequences of the current database. Add the `S` modifier to also show all system objects. If you specify a sequence name or a [pattern](#patterns), it will show the details of matching sequences. Add the `+` modifier to show additional information.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `\dt[S+] [<pattern]`                               | Show the tables of the current database. Add the `S` modifier to also show all system objects. If you specify a table name or a [pattern](#patterns), it will show the details of matching tables. Add the `+` modifier to show additional information.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `\dT[S+] [<pattern]`                               | Show the <InternalLink path="enum">user-defined types</InternalLink> in the current database. Add the `S` modifier to also show all system objects. If you specify a type name or a [pattern](#patterns), it will show the details of matching types. Add the `+` modifier to show additional information.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `\du[S+] [<pattern]`                               | Show the <InternalLink path="authorization">roles</InternalLink> of the current database. Add the `S` modifier to also show all system objects. If you specify a role name or a [pattern](#patterns), it will show the details of matching roles. Add the `+` modifier to show additional information.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `\dv[S+] [<pattern]`                               | Show the views of the current database. Add the `S` modifier to also show all system objects. If you specify a view name or a [pattern](#patterns), it will show the details of matching views. Add the `+` modifier to show additional information.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `\r`                                               | Resets the query input buffer, clearing all SQL statements that have been entered but not yet executed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `\statement-diag list`                             | List available <InternalLink path="cockroach-statement-diag">diagnostic bundles</InternalLink>.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `\statement-diag download <bundle-id> [<filename]` | Download diagnostic bundle.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `\i <filename>`                                    | Reads and executes input from the file `<filename`, in the current working directory.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `\ir <filename>`                                   | Reads and executes input from the file `<filename`.<br />When invoked in the interactive shell, `\i` and `\ir` behave identically (i.e., CockroachDB looks for `<filename` in the current working directory). When invoked from a script, CockroachDB looks for `<filename` relative to the directory in which the script is located.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `\echo <arguments>`                                | Evaluate the `<arguments` and print the results to the standard output.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `\x <boolean>`                                     | When `true`/`on`/`yes`/`1`, <InternalLink path="cockroach-sql">sets the display format</InternalLink> to `records`. When `false`/`off`/`no`/`0`, sets the session's format to the default (`table`/`tsv`).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |

#### Patterns

Commands use the SQL <InternalLink path="scalar-expressions#string-pattern-matching">`LIKE` syntax</InternalLink> for string pattern matching, not POSIX regular expressions.

For example to list all schemas that begin with the letter "p" you'd use the following pattern:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
\dn p%
```

```
List of schemas:
      Name     | Owner
---------------+--------
  pg_catalog   | NULL
  pg_extension | NULL
  public       | admin
(3 rows)
```

### 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>`. 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`.
  * `on`, `yes`, and `1` are aliases for `true`, and `off`, `no`, and `0` are aliases for `false`.

| Client Options                                        | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <a id="sql-option-auto-trace" /> `auto_trace`         | For 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.<br /><br />**Default:** `off`<br /><br />To enable this option, run `\set auto_trace on`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| <a id="sql-option-border" /> `border`                 | Display a border around the output of the SQL statement when using the `table` display format. Set the level of borders using `border=<level` to configure how many borders and lines are in the output, where `<level` is an integer between 0 and 3. The higher the integer, the more borders and lines are in the output. <br />A level of `0` shows the output with no outer lines and no row line separators. <br />A level of `1` adds row line separators. A level of `2` adds an outside border and no row line separators. A level of `3` adds both an outside border and row line separators. <br /><br />**Default:** `0` <br /><br />To change this option, run `\set border=<level`. <InternalLink path="cockroach-sql#show-borders-around-the-statement-output-within-the-sql-shell">See an example</InternalLink>. |
| <a id="sql-option-check-syntax" /> `check_syntax`     | Validate 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.<br /><br />**Default:** `true` for <InternalLink path="cockroach-sql#session-and-output-types">interactive sessions</InternalLink>; `false` otherwise.<br /><br />To disable this option, run `\unset check_syntax`.                                                                                                                                                                                                                                                                                                                                                                                                                               |
| <a id="sql-option-display-format" /> `display_format` | How to display table rows printed within the interactive SQL shell. Possible values: `tsv`, `csv`, `table`, `raw`, `records`, `sql`, `html`.<br /><br />**Default:** `table` for sessions that <InternalLink path="cockroach-sql#session-and-output-types">output on a terminal</InternalLink>; `tsv` otherwise<br /><br />To change this option, run `\set display_format <format>`. <InternalLink path="cockroach-sql#make-the-output-of-show-statements-selectable">See an example</InternalLink>.                                                                                                                                                                                                                                                                                                                             |
| <a id="sql-option-echo" /> `echo`                     | Reveal the SQL statements sent implicitly by the SQL shell.<br /><br />**Default:** `false`<br /><br />To enable this option, run `\set echo`. <InternalLink path="cockroach-sql#reveal-the-sql-statements-sent-implicitly-by-the-command-line-utility">See an example</InternalLink>.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| <a id="sql-option-errexit" /> `errexit`               | Exit the SQL shell upon encountering an error.<br /><br />**Default:** `false` for <InternalLink path="cockroach-sql#session-and-output-types">interactive sessions</InternalLink>; `true` otherwise<br /><br />To enable this option, run `\set errexit`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| <a id="sql-option-prompt1" /> `prompt1`               | Customize the interactive prompt within the SQL shell. See [Customizing the prompt](#customizing-the-prompt) for information on the available prompt variables.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| <a id="sql-option-show-times" /> `show_times`         | Reveal the time a query takes to complete. Possible values:<br />                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |

* `execution` time refers to the time taken by the SQL execution engine to execute the query.
* `network` time refers to the network latency between the server and the SQL client command.
* `other` time refers to all other forms of latency affecting the total query completion time, including query planning.

**Default:** `true`<br /><br />To disable this option, run `\unset show_times`.

#### Customizing the prompt

The `\set prompt1` option allows you to customize the interactive prompt in the SQL shell. Use the following prompt variables to set a custom prompt.

| Prompt variable | Description                                         |
| --------------- | --------------------------------------------------- |
| `%>`            | The port of the node you are connected to.          |
| `%/`            | The current database name.                          |
| `%M`            | The fully qualified host name and port of the node. |
| `%m`            | The fully qualified host name of the node.          |
| `%n`            | The username of the connected SQL user.             |
| `%x`            | The transaction status of the current statement.    |

For example, to change the prompt to just the user, host, and database:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
\set prompt1 %n@%m/%/
```

```
maxroach@blue-dog-595.g95.cockroachlabs.cloud/defaultdb>
```

### Help

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

| Command                                    | Usage                                                    |
| ------------------------------------------ | -------------------------------------------------------- |
| `\h`<br /><br />`??`                       | List all available SQL statements, by category.          |
| `\hf`                                      | List all available SQL functions, in alphabetical order. |
| `\h <statement>`<br /><br />`<statement ?` | View help for a specific SQL statement.                  |
| `\hf <function>`<br /><br />`<function ?`  | View help for a specific SQL function.                   |

<a id="locality-example" />

#### Examples

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> \h UPDATE
```

```
Command:     UPDATE
Description: update rows of a table
Category:    data manipulation
Syntax:
UPDATE

[[AS] ] SET ... [WHERE ] [RETURNING ]
See also:
SHOW TABLES
INSERT
UPSERT
DELETE
https://www.cockroachlabs.com/docs/v26.2/update.html
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> \hf uuid\_v4
```

```
Function: uuid\_v4
Category: built-in functions
Returns a UUID.
Signature Category
uuid\_v4() -> bytes [ID Generation]
See also:
https://www.cockroachlabs.com/docs/v26.2/functions-and-operators.html
```

### Shortcuts

Note: macOS users may need to manually enable Alt-based shortcuts in their terminal configuration. See the section [macOS terminal configuration](#macos-terminal-configuration) below for details.

| Shortcut                                                                | Description                                                                        |
| ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| Tab                                                                     | Use [context-sensitive command completion](#tab-completion).                       |
| Ctrl+C                                                                  | Clear/cancel the input.                                                            |
| Ctrl+M, Enter                                                           | New line/enter.                                                                    |
| Ctrl+O                                                                  | Force a new line on the current statement, even if the statement has a semicolon.  |
| Ctrl+F, Right arrow                                                     | Forward one character.                                                             |
| Ctrl+B, Left arrow                                                      | Backward one character.                                                            |
| Alt+F, Ctrl+Right arrow                                                 | Forward one word.                                                                  |
| Alt+B, Ctrl+Left arrow                                                  | Backward one word.                                                                 |
| Ctrl+L                                                                  | Refresh the display.                                                               |
| Delete                                                                  | Delete the next character.                                                         |
| Ctrl+H, Backspace                                                       | Delete the previous character.                                                     |
| Ctrl+D                                                                  | Delete the next character, or terminate the input if the input is currently empty. |
| Alt+D, Alt+Delete                                                       | Delete next word.                                                                  |
| Ctrl+W, Alt+Backspace                                                   | Delete previous word.                                                              |
| Ctrl+E, End                                                             | End of line.                                                                       |
| Alt+>, Ctrl+End                                                         | Move cursor to the end of a multi-line statement.                                  |
| Ctrl+A, Home                                                            | Move cursor to the beginning of the current line.                                  |
| Alt+\<, Ctrl+Home                                                       | Move cursor to the beginning of a multi-line statement.                            |
| Ctrl+T                                                                  | Transpose current and next characters.                                             |
| Ctrl+K                                                                  | Delete from cursor position until end of line.                                     |
| Ctrl+U                                                                  | Delete from beginning of line to cursor position.                                  |
| Alt+Q                                                                   | Reflow/reformat the current line.                                                  |
| Alt+Shift+Q, Alt+\`                                                     | Reflow/reformat the entire input.                                                  |
| Alt+L                                                                   | Convert the current word to lowercase.                                             |
| Alt+U                                                                   | Convert the current word to uppercase.                                             |
| Alt+.                                                                   | Toggle the visibility of the prompt.                                               |
| Alt+2, Alt+F2                                                           | Invoke external editor on current input.                                           |
| Alt+P, Up arrow                                                         | Recall previous history entry.                                                     |
| Alt+N, Down arrow                                                       | Recall next history entry.                                                         |
| Ctrl+R                                                                  | Start searching through input history.                                             |
| When searching for history entries, the following shortcuts are active: |                                                                                    |
| Shortcut                                                                | Description                                                                        |
| ----------------                                                        | ----------------------------------------------------                               |
| Ctrl+C, Ctrl+G                                                          | Cancel the search, return to normal mode.                                          |
| Ctrl+R                                                                  | Recall next entry matching current search pattern.                                 |
| Enter                                                                   | Accept the current recalled entry.                                                 |
| Backspace                                                               | Delete previous character in search pattern.                                       |
| Other                                                                   | Add character to search pattern.                                                   |

#### Tab completion

The SQL client offers context-sensitive tab completion when entering commands. Use the \*\*Tab\*\* key on your keyboard when entering a command to initiate the command completion interface. You can then navigate to database objects, keywords, and functions using the arrow keys. Press the \*\*Tab\*\* key again to select the object, function, or keyword from the command completion interface and return to the console.

### macOS terminal configuration

In \*\*Apple Terminal\*\*:

1. Navigate to "Preferences", then "Profiles", then "Keyboard".
2. Enable the checkbox "Use Option as Meta Key".
   <img src="https://mintcdn.com/cockroachlabs/H2p_QgztDgzpDDkl/images/v26.2/terminal-configuration.png?fit=max&auto=format&n=H2p_QgztDgzpDDkl&q=85&s=6a9c5c09424be025718951e51ffa8cca" alt="Apple Terminal Alt key configuration" width="1536" height="1280" data-path="images/v26.2/terminal-configuration.png" />
   In \*\*iTerm2\*\*:
3. Navigate to "Preferences", then "Profiles", then "Keys".
4. Select the radio button "Esc+" for the behavior of the Left Option Key.
   <img src="https://mintcdn.com/cockroachlabs/7A5lSB6m0mXfjOZl/images/v26.2/iterm2-configuration.png?fit=max&auto=format&n=7A5lSB6m0mXfjOZl&q=85&s=8ca32e054a9c048586f6367c83a89eea" alt="iTerm2 Alt key configuration" width="2036" height="1164" data-path="images/v26.2/iterm2-configuration.png" />

### Error messages and `SQLSTATE` codes

When CockroachDB encounters a SQL error, it returns the following information to the client (whether `cockroach-sql` or another client application):

1. An error message, prefixed with [the "Severity" field of the PostgreSQL wire protocol](https://www.postgresql.org/docs/current/protocol-error-fields.html). For example, `ERROR: insert on table "shipments" violates foreign key constraint "fk\_customers"`.
2. A [5-digit `SQLSTATE` error code](https://wikipedia.org/wiki/SQLSTATE) as defined by the SQL standard. For example, `SQLSTATE: 23503`.
   For example, the following query (taken from <InternalLink path="foreign-key#add-multiple-foreign-key-constraints-to-a-single-column">this example of adding multiple foreign key constraints</InternalLink>) results in a SQL error, and returns both an error message and a `SQLSTATE` code as described above.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> INSERT INTO shipments (carrier, status, customer\_id) VALUES ('DHL', 'At facility', 2000);
```

```
ERROR: insert on table "shipments" violates foreign key constraint "fk\_customers"
SQLSTATE: 23503
DETAIL: Key (customer\_id)=(2000) is not present in table "customers".
```

The [`SQLSTATE` code](https://wikipedia.org/wiki/SQLSTATE) in particular can be helpful in the following ways:

* It is a standard SQL error code that you can look up in documentation and search for on the web. For any given error state, CockroachDB tries to produce the same `SQLSTATE` code as PostgreSQL.
* If you are developing automation that uses the CockroachDB SQL shell, it is more reliable to check for `SQLSTATE` values than for error message strings, which are likely to change.

## Examples

### Start a SQL shell

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

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
# Using the --url flag:
$ cockroach-sql \
--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"
```

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
# Using standard connection flags:
$ cockroach-sql \
--certs-dir=certs \
--user=maxroach \
--host=12.345.67.89 \
--database=critterdb
```

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

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
# Using the --url flag:
$ cockroach-sql \
--url="postgresql://maxroach@12.345.67.89:26257/critterdb?sslmode=disable"
```

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
# Using standard connection flags:
$ cockroach-sql --insecure \
--user=maxroach \
--host=12.345.67.89 \
--database=critterdb
```

### Execute SQL statement within the SQL shell

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

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> CREATE TABLE animals (id INT PRIMARY KEY DEFAULT unique\_rowid(), name STRING);
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> INSERT INTO animals (name) VALUES ('bobcat'), ('🐢 '), ('barn owl');
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SELECT \* FROM animals;
```

```
id | name
---------------------+-----------
710907071259213825 | bobcat
710907071259279361 | 🐢
710907071259312129 | barn owl
(3 rows)
```

### Execute SQL statements from the command line

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

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
# Statements with a single --execute flag:
$ cockroach-sql --insecure \
--execute="CREATE TABLE roaches (name STRING, country STRING); INSERT INTO roaches VALUES ('American Cockroach', 'United States'), ('Brownbanded Cockroach', 'United States')" \
--user=maxroach \
--host=12.345.67.89 \
--database=critterdb
```

```
CREATE TABLE
INSERT 2
```

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
# Statements with multiple --execute flags:
$ cockroach-sql --insecure \
--execute="CREATE TABLE roaches (name STRING, country STRING)" \
--execute="INSERT INTO roaches VALUES ('American Cockroach', 'United States'), ('Brownbanded Cockroach', 'United States')" \
--user=maxroach \
--host=12.345.67.89 \
--database=critterdb
```

```
CREATE TABLE
INSERT 2
```

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

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
# Statements with the echo command:
$ echo "SHOW TABLES; SELECT \* FROM roaches;" | cockroach-sql --insecure --user=maxroach --host=12.345.67.89 --database=critterdb
```

```
schema\_name | table\_name | type | owner | estimated\_row\_count | locality
--------------+------------+-------+-------+---------------------+-----------
public | animals | table | demo | 0 | NULL
public | roaches | table | demo | 0 | NULL
(2 rows)
name | country
------------------------+----------------
American Cockroach | United States
Brownbanded Cockroach | United States
```

### 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:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --insecure \
--execute="SELECT '🐥' AS chick, '🐢' AS turtle" \
--user=maxroach \
--host=12.345.67.89 \
--database=critterdb
```

```
chick | turtle
--------+---------
🐥 | 🐢
```

However, you can explicitly set `--format` to another format (e.g., `tsv` or `html`):

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --insecure \
--format=tsv \
--execute="SELECT '🐥' AS chick, '🐢' AS turtle" \
--user=maxroach \
--host=12.345.67.89 \
--database=critterdb
```

```
chick turtle
🐥 🐢
```

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --insecure \
--format=html \
--execute="SELECT '🐥' AS chick, '🐢' AS turtle" \
--user=maxroach \
--host=12.345.67.89 \
--database=critterdb
```

```

| row | chick | turtle |
| --- | --- | --- |
| 1 | 🐥 | 🐢 |
|  |  |  |
| --- | --- | --- |
| 1 row | | |

```

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

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --insecure \
--execute="SELECT '🐥' AS chick, '🐢' AS turtle" > out.txt \
--user=maxroach \
--host=12.345.67.89 \
--database=critterdb
```

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cat out.txt
```

```
1 row
chick	turtle
🐥	🐢
```

However, you can explicitly set `--format` to another format (e.g., `table`):

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --insecure \
--format=table \
--execute="SELECT '🐥' AS chick, '🐢' AS turtle" > out.txt \
--user=maxroach \
--host=12.345.67.89 \
--database=critterdb
```

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cat out.txt
```

```
  chick | turtle
--------+---------
  🐥    | 🐢
(1 row)
```

### Show borders around the statement output within the SQL shell

To display outside and inside borders in the statement output, set the `border` [SQL shell option](#client-side-options) to `3`.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
\set border=3
SELECT * FROM animals;
```

```
+--------------------+----------+
|         id         |   name   |
+--------------------+----------+
| 710907071259213825 | bobcat   |
+--------------------+----------+
| 710907071259279361 | 🐢       |
+--------------------+----------+
| 710907071259312129 | barn owl |
+--------------------+----------+
```

### Make the output of `SHOW` statements selectable

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

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --insecure \
--format=raw \
--user=maxroach \
--host=12.345.67.89 \
--database=critterdb
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SHOW CREATE customers;
```

```
# 2 columns
# row 1
## 14
test.customers
## 185
CREATE TABLE customers (
	id INT NOT NULL,
	email STRING NULL,
	CONSTRAINT "primary" PRIMARY KEY (id ASC),
	UNIQUE INDEX customers_email_key (email ASC),
	FAMILY "primary" (id, email)
)
# 1 row
```

When `--format` is not set to `raw`, you can use the `display_format` [SQL shell option](#client-side-options) to change the output format within the interactive session:

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> \set display_format raw
```

```
# 2 columns
# row 1
## 14
test.customers
## 185
CREATE TABLE customers (
  id INT NOT NULL,
  email STRING NULL,
  CONSTRAINT "primary" PRIMARY KEY (id ASC),
  UNIQUE INDEX customers_email_key (email ASC),
  FAMILY "primary" (id, email)
)
# 1 row
```

### Execute SQL statements from a file

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

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cat statements.sql
```

```
CREATE TABLE roaches (name STRING, country STRING);
INSERT INTO roaches VALUES ('American Cockroach', 'United States'), ('Brownbanded Cockroach', 'United States');
```

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --insecure \
--user=maxroach \
--host=12.345.67.89 \
--database=critterdb \
-f statements.sql
```

```
CREATE TABLE
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.

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> \! cat test.csv
```

```
12, 13, 14
10, 20, 30
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> CREATE TABLE csv (x INT, y INT, z INT);
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> \| IFS=","; while read a b c; do echo "insert into csv values ($a, $b, $c);"; done < test.csv;
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SELECT * FROM csv;
```

```
  x  | y  | z
-----+----+-----
  12 | 13 | 14
  10 | 20 | 30
```

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

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> CREATE TABLE for_loop (x INT);
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> \| for ((i=0;i<10;++i)); do echo "INSERT INTO for_loop VALUES ($i);"; done
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> SELECT * FROM for_loop;
```

```
  x
-----
  0
  1
  2
  3
  4
  5
  6
  7
  8
  9
```

### Allow potentially unsafe SQL statements

The [`--safe-updates` flag](#flag-safe-updates) 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:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --insecure --execute="SELECT * FROM db1.t1"
```

```
  id | name
-----+-------
   1 | a
   2 | b
   3 | c
   4 | d
   5 | e
   6 | f
   7 | g
   8 | h
   9 | i
  10 | j
-----+-------
(10 rows)
```

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --insecure --execute="DELETE FROM db1.t1"
```

```
Error: pq: rejected: DELETE without WHERE clause (sql_safe_updates = true)
Failed running "sql"
```

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

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --insecure --safe-updates=false --execute="DELETE FROM db1.t1"
```

```
DELETE 10
```

Potentially unsafe SQL statements can also be allowed/disallowed for an entire session via the <InternalLink path="set-vars">`sql_safe_updates` session variable</InternalLink>. For a complete list of these statements, refer to the session variable documentation.

### 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:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --insecure \
--execute="CREATE TABLE t1 (id INT PRIMARY KEY, name STRING)" \
--execute="INSERT INTO t1 VALUES (1, 'a'), (2, 'b'), (3, 'c')" \
--user=maxroach \
--host=12.345.67.89 \
--database=db1
--echo-sql
```

```
# Server version: CockroachDB CCL f8f3c9317 (darwin amd64, built 2017/09/13 15:05:35, go1.8) (same version as client)
# Cluster ID: 847a4ba5-c78a-465a-b1a0-59fae3aab520
> SET sql_safe_updates = TRUE
> CREATE TABLE t1 (id INT PRIMARY KEY, name STRING)
CREATE TABLE
> INSERT INTO t1 VALUES (1, 'a'), (2, 'b'), (3, 'c')
INSERT 3
```

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

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --insecure \
--user=maxroach \
--host=12.345.67.89 \
--database=db1
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> \set echo
```

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
> INSERT INTO db1.t1 VALUES (4, 'd'), (5, 'e'), (6, 'f');
```

```
> INSERT INTO db1.t1 VALUES (4, 'd'), (5, 'e'), (6, 'f');
INSERT 3

Time: 2.426534ms

> SHOW TRANSACTION STATUS
> SHOW DATABASE
```

### Repeat a SQL statement

Repeating SQL queries on a table can be useful for monitoring purposes. With the `--watch` flag, you can repeat the statements specified with a `--execute` or `-e` flag periodically, until a SQL error occurs or the process is terminated.

For example, if you want to monitor the number of queries running on the current node, you can use `cockroach-sql` with the `--watch` flag to query the node's `crdb_internal.node_statement_statistics` table for the query count:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --insecure \
--execute="SELECT SUM(count) FROM crdb_internal.node_statement_statistics" \
--watch 1m
```

```
  sum
-------
  926
(1 row)
  sum
--------
  4227
(1 row)
^C
```

In this example, the statement is executed every minute. We let the process run for a couple minutes before terminating it with **Ctrl+C**.

### Connect to a cluster listening for Unix domain socket connections

To connect to a cluster that is running on the same machine as your client and is listening for [Unix domain socket](https://wikipedia.org/wiki/Unix_domain_socket) connections, <InternalLink path="connection-parameters#example-uri-for-a-unix-domain-socket">specify a Unix domain socket URI</InternalLink> with the `--url` connection parameter.

For example, suppose you start a single-node cluster with the following <InternalLink path="cockroach-start-single-node">`cockroach start-single-node`</InternalLink> command:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach start-single-node --insecure --socket-dir=/tmp
```

```
CockroachDB node starting at  (took 1.3s)
build:               CCL  @
webui:               http://Jesses-MBP-2:8080
sql:                 postgresql://root@Jesses-MBP-2:26257?sslmode=disable
RPC client flags:    ./cockroach <client cmd> --host=Jesses-MBP-2:26257 --insecure
socket:              /tmp/.s.PGSQL.26257
logs:                /Users/jesseseldess/Downloads/cockroach-.darwin-10.9-amd64/cockroach-data/logs
temp dir:            /Users/jesseseldess/Downloads/cockroach-.darwin-10.9-amd64/cockroach-data/cockroach-temp805054895
external I/O path:   /Users/jesseseldess/Downloads/cockroach-.darwin-10.9-amd64/cockroach-data/extern
store[0]:            path=/Users/jesseseldess/Downloads/cockroach-.darwin-10.9-amd64/cockroach-data
storage engine:      pebble
status:              initialized new cluster
clusterID:           455ad71d-21d4-424a-87ad-8097b6b5b99f
nodeID:              1
```

To connect to this cluster with a socket:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
$ cockroach-sql --url='postgres://root@?host=/tmp&port=26257'
```

<a id="cost-based-optimizer-kl" />

## Known limitations

* CockroachDB imposes a hard limit of 16MiB on the data input for a single statement passed to CockroachDB from a client (including the SQL shell). We do not recommend attempting to execute statements from clients with large input.
* In the <InternalLink path="cockroach-sql">built-in SQL shell</InternalLink>, using the <InternalLink path="cockroach-sql#commands">`\|`</InternalLink> operator to perform a large number of inputs from a file can cause the server to close the connection. This is because `\|` sends the entire file as a single query to the server, which can exceed the upper bound on the size of a packet the server can accept from any client (16MB). As a workaround, <InternalLink path="cockroach-sql#execute-sql-statements-from-a-file">execute the file from the command line</InternalLink> with `cat data.sql | cockroach sql` instead of from within the interactive shell.

## See also

* <InternalLink path="connection-parameters">Client Connection Parameters</InternalLink>
* <InternalLink path="cockroach-demo">`cockroach demo`</InternalLink>
* <InternalLink path="cockroach-commands">`cockroach` Commands Overview</InternalLink>
* <InternalLink path="sql-statements">SQL Statements</InternalLink>
* <InternalLink path="learn-cockroachdb-sql">Learn CockroachDB SQL</InternalLink>
